Correct way of binding multiple attribute changes to a Backbone.js model

ericbae picture ericbae · Nov 25, 2011 · Viewed 22.3k times · Source

I have the following code, where I bind a change to a single attribute "attribute_1".

var Mine = Backbone.Model.extend({
  initialize: function() {
    this.bind("change:attribute_1", function() {
      console.log('changed!');
    });
  }
});

How do I bind two attributes? This doesn't work:

var Mine = Backbone.Model.extend({
  initialize: function() {
    this.bind("change:attribute_1, change:attribute_2", function() {
      console.log('changed!');
    });
  }
});

Nor does this:

var Mine = Backbone.Model.extend({
  initialize: function() {
    this.bind("change:attribute_1 change:attribute_2", function() {
      console.log('changed!');
    });
  }
});

Answer

Rob Hruska picture Rob Hruska · Feb 29, 2012

As of Backbone.js 0.9.0, the bind() function (which has been renamed to on()) supports a space-delimited list of events:

model.on("change:title change:author", ...)

// equivalent to

model.bind("change:title change:author", ...)