fredag 20 september 2013

Backgrid and CouchDB changes

According to the Backgrid documentation, the way to save our Backbone models to the database is by building our models like:
var MyModel = 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();
    });
  }
});
That looks good at first, but will become a real problem if we use CouchDB and _changes to get real time data in our app. What happens is: We change our model -> it get persisted to Couch. Couch informs all listeners that a document has been changed, which meens that our Backgrid app will change the model, which in turn will trigger the change event in our model. Then: a new save to Couch and so forth. Can anybody spot an infinite loop? What we did instead was to have our models simple like this:
var MyModel = Backbone.Model.extend({
});
And then, in our view where we instansiate the grid, include the following.

var bg = new Backgrid.Grid({
    columns: gridColumns,
    collection: self.collection,
    footer: footer
});

bg.listenTo(self.collection,"backgrid:edited",function(model){
    if(Object.getOwnPropertyNames(model.changed).length > 0){
        model.save();
    }
});

Inga kommentarer:

Skicka en kommentar