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();
    }
});

tisdag 17 september 2013

How to solve $.browser errors when using Backbone + CouchDB

We are building an application using Backbone + Marionette + Require, and decided to go for CouchDB as our backend. Since all we are doing in the backend is basic CRUD we beleive that going directly towards a Couch db will really speed things up.

It's really quite simple to set up, but there are some caveats that has to be resolved.

First of: The jquery-couch is using a $.browser function, which is really old and not existing in newer jQuery versions. To solve that, you can either rely on an jQuery version from the Jurassic period, or you can include the jquery-migrate.js