sri85
sri85

Reputation: 337

Backbone model fires "change" event twice

I just started working on backbonejs about a week ago and i discovered that my model is being saved twice on listening to calling "change" event from my view .

Basically what i have is a table which user can edit, whenever the user updates the cell value i want to push it to server , for which i have defined a "change" method and i am calling it every time a cell is updated.

The problem i am facing is that id model is saved twice on calling "change" event.

If i pass wait:true for model.save, change event is fired thrice

AM i doing something wrong ,or am is missing something obviuos? Any help would be greatly appreciated

Below is my code

var Territory = Backbone.Model.extend({
   initialize: function () {
        Backbone.Model.prototype.initialize.apply(this, arguments);
        this.on("change", function (model, options) {
            if (options && options.save === false) return;
            model.save();
        });
    }
});

var Territories = Backbone.Collection.extend({
    model: Territory,
    url: "js/bookings.json"
});
var territories = new Territories();

var columns = [{
    name: "bookingId",
    label: "ID",
    editable: false,
    cell: Backgrid.IntegerCell.extend({
        orderSeparator: ''
    })
}, {
    name: "bookingTime",
    label: "Time",
    cell: "string"
}, {
    name: "bookingUser",
    label: "Name",
    cell: "string"
}, {
    name: "reserveDate",
    label: "Date",
    cell: "string"
}, {
    name: "bookingEmail",
    label: "Email",
    cell: "string"
}];

var grid = new Backgrid.Grid({
    columns: columns,
    collection: territories

});

grid.listenTo(territories, "change", function () {
    alert(territories.pluck('bookingId'))
});

Any help would be greatly appreciated.

Upvotes: 3

Views: 1800

Answers (1)

sri85
sri85

Reputation: 337

My BAD, the 2 events were one fired from the client to save the data and other was the response from the server after the data was saved .

Upvotes: 4

Related Questions