如何访问XHR对象,使backbone.model保存

Lor*_*ard 3 javascript ajax jquery backbone.js

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

$.ajax().fail(function (XHR) {
     // some code
});
Run Code Online (Sandbox Code Playgroud)

保存骨干模型时:

var MyView = Backbone.View.extend({

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


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

});
Run Code Online (Sandbox Code Playgroud)

保存backbone.modelonError服务器事件时,如何获取XHR ?

Edw*_*ith 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);            
    }
});
Run Code Online (Sandbox Code Playgroud)

另外,请注意,Model.save()需要2个参数 - 在保存之前要更改的属性,以及作为第二个参数的options hash.

这是一个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();
Run Code Online (Sandbox Code Playgroud)

更新的jsFiddle:http: //jsfiddle.net/edwardmsmith/8AVjy/14/