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

时间:2012-08-27 14:25:57

标签: javascript ajax jquery backbone.js

通过使用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?

1 个答案:

答案 0 :(得分: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/