3

通过使用 ajax,我可以简单地访问 XHR 对象:

$.ajax().fail(function (XHR) {
     // some code
});

保存主干模型时:

var MyView = Backbone.View.extend({

    saveModel: function () {
        this.myModel.save({
            error: this.onError
        });
    }


    onError: function (xhr) {
       // how to access xhr?
    }

});

backbone.model保存onError 服务器事件时应该如何获取 XHR ?

4

1 回答 1

5

当您调用通过 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/

于 2012-08-27T15:14:49.733 回答