Dom Christie

Backbone.js Patterns Pt.3: Excluding non-persisted attributes

As I mentioned in the previous post, the toJSON method is used to customise the data sent to the server.

Often you’ll have attributes on your model that you don’t want to be persisted e.g. isSelected. You could customise the toJSON method on a model-by-model basis, but given that excluding attributes is quite common, we can just include a list of attributes we’d like removed, and modify Backbone.Model.prototype.toJSON, to handle it.

First, we’ll add an excludeFromJSON property to the class definition. This should be an array of attribute keys you'd like to exclude:

var Post = Backbone.Model.extend({
  excludeFromJSON: [ 'isSelected' ]
});

We can then build on our previous toJSON method to exclude those attributes:

(function() {
  var oldToJSON = Backbone.Model.prototype.toJSON;
  Backbone.Model.prototype.toJSON = function() {
    var json = oldToJSON.apply(this, arguments),
        excludeFromJSON = this.excludeFromJSON;
    if(excludeFromJSON) {
      _.each(excludeFromJSON, function(key) {
        delete json[key];
      });
    }
    return humps.decamelizeKeys(json);
  };
})();

This new Backbone.Model.prototype.toJSON calls the old method to retrieve a copy of the model's attributes, then deletes any properties whose keys are in the excludeFromJSON array. The modified attributes are finally “decamelized”. If you don’t wish to include my humps library, then just return json;.

Feedback/questions welcome via Twitter, or email.