Search code examples
javascriptbackbone.jsbackgrid

backbone backgrid: how to avoid double change event


I have a backbone/backgrid editable grid, and everytime I edit a cell the "change" event is fired up twice and I end up making two separate PUT requests.

I know that this happens because the "change" event fires once when I edit it in the cell, and another when the data comes back from the server; and that the behaviour could be avoided by passing {wait: true} to the save method, but I don't know where I need to overload it.

My model declaration is like this:

var Redirects = Backbone.Model.extend({
    urlRoot: '/global/redirects',
    initialize: function () {
        Backbone.Model.prototype.initialize.apply(this, arguments);

        this.on("change", function (model, options) {
            if (options && options.save === false) return;
            model.save({
                error: alertMe
            });
        });

        this.on('fetch request', function (e) {
            loadingOn(e);
        });

        this.on('sync error', function (e) {
            loadingOff(e);
        });

        this.on('error', function(e, resp){
            alertMe(e, resp);
        });
    }
});

Solution

  • You shouldn't receive a 2nd change event when a Model is synced from the server, regardless of the wait option.

    The problem in your save call is that you haven't specified the attributes hash, i.e. the first parameter. If you don't have any attributes to modify, which considering you are firing save for a change event, that's probably the case, you will need the following:

        this.on("change", function (model, options) {
            if (options && options.save === false) return;
            model.save(null, {error: alertMe});
        });
    

    What was actually happening was that you were setting error as an attribute on the model, and that triggered the change event.