3

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.

Vitalii Petrychuk
  • 14,035
  • 8
  • 51
  • 55
sri85
  • 337
  • 2
  • 19
  • Not enough shown here to identify where your code is causing change to fire twice. Is Backgrid your view? Is the listener attached to grid also firing the alert twice for a given change? Where do you actually do something that sets values on your models? – kinakuta Jun 14 '13 at 18:48
  • Add an `all` event, and `console.log` out some information on exactly what events are happening, and with what param. That may help you solve. – Bart Jun 14 '13 at 19:17

1 Answers1

4

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 .

sri85
  • 337
  • 2
  • 19