Backbone.js collections can listen to their models’ changes

February 12th, 2012 by Gareth / Comments

I wanted to know if Backbone.js collections can listen to their models’ events. It turns out they can. In your collection you just need to use the same binding mechanism that you would in a view.

	initialize:
  function() {
    this.on("change:name", this.changeName);
    this.on("change:age", this.changeAge);
  },
	

Here’s a JSFiddle test :

I looked in the Backbone.js source code and found where it happens :

	// Internal method called every time a model in the set fires an event.
// Sets need to update their indexes when models change ids. All other
// events simply proxy through. "add" and "remove" events that originate
// in other collections are ignored.
_onModelEvent : function(ev, model, collection, options) {
    if ((ev == 'add' || ev == 'remove') && collection != this) return;
    if (ev == 'destroy') {
        this._remove(model, options);
    }
    if (model && ev === 'change:' + model.idAttribute) {
        delete this._byId[model.previous(model.idAttribute)];
        this._byId[model.id] = model;
    }
    this.trigger.apply(this, arguments);
}
	

Javascript

My Micro-SAAS Journey

Get the inside story as I work out how to create a micro-SAAS