当您调用通过 Backbone.Sync 的任何函数时,Backbone 返回对 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);
}
});
另外,请注意,它Model.save()
需要 2 个参数 - 保存前要更改的属性,以及选项哈希作为第二个参数。
这是一个 jsFiddle 示例:http: //jsfiddle.net/edwardmsmith/8AVjy/7/
发表评论:
我从来没有真正需要这样做,但这是我可能会做的:
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();
为此更新了 jsFiddle:http: //jsfiddle.net/edwardmsmith/8AVjy/14/