Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Access XHR Object making backbone.model save

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?.

like image 566
Lorraine Bernard Avatar asked Jan 29 '26 15:01

Lorraine Bernard


1 Answers

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/

like image 89
Edward M Smith Avatar answered Feb 01 '26 04:02

Edward M Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!