Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!');
    });
  }
});
like image 863
ericbae Avatar asked Nov 25 '11 00:11

ericbae


2 Answers

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", ...)
like image 143
Rob Hruska Avatar answered Oct 24 '22 09:10

Rob Hruska


I don't know if such a "bulk-bind" function exists (you could open a feature request for it, it seems useful).

You can bind them separately:

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

Or you can listen to all changes (and then filter in the listener):

var Mine = Backbone.Model.extend({
  initialize: function() {
    var listener = function() { console.log('changed'); };
    this.bind("change", listener);
  }
});
like image 24
Thilo Avatar answered Oct 24 '22 09:10

Thilo