By using ajax I can access the XHR Object simply making:
$.ajax().fail(function (XHR) {
// some code
});
When saving a backbone model:
var MyView = Backbone.View.extend({
saveModel: function () {
this.myModel.save({
error: this.onError
});
}
onError: function (xhr) {
// how to access xhr?
}
});
How should I get XHR when I save a backbone.model onError server event?.
When you call any of the functions that go through Backbone.Sync, Backbone returns a reference to the XHR:
var MyModel = Backbone.Model.extend({
url: "/some/path/that/is/an/error/"
});
var myModel = new MyModel();
xhr = myModel.save( {} , {
error: function(model, response) {
console.log(xhr);
}
});
Also, note that Model.save() takes 2 arguments - properties to change before saving, and the options hash as a second argument.
Here's a jsFiddle example: http://jsfiddle.net/edwardmsmith/8AVjy/7/
Post Comment:
I've never really needed to do it, but this is what I'd probably do:
var MyModel = Backbone.Model.extend({
url: "/some/path/that/is/an/error/"
});
var MyView = Backbone.View.extend({
saveModel: function () {
that = this;
xhr = this.model.save({}, {
error: function (model, resp) {
that.onError(xhr);
}
});
},
onError: function (xhr) {
// how to access xhr?
console.log(xhr);
}
});
var myModel = new MyModel();
var myView = new MyView({model: myModel});
myView.saveModel();
An updated jsFiddle for this: http://jsfiddle.net/edwardmsmith/8AVjy/14/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With