Search code examples
javascriptbackbone.js

Backbone's change event for models and collections


I am searching online to no avail - what is the difference between:

this.listenTo(this.collection, 'add reset remove', this.render);

…and:

this.listenTo(this.collection, 'change', this.render);

I am trying to find out what the change event encapsulates. It's really hard to find this info.

Furthermore, in the this.render callback - how do I find out what was changed? Do I have to inspect the Backbone model/collection myself or is there a higher level way to do that?


Solution

  • The annotated Backbone source is really good for figuring out stuff like this.

    According to http://backbonejs.org/docs/backbone.html#section-144 the 'change' event is fired whenever a model in the collection is changed.

    The change event is triggered with the same arguments as if triggered on the model, where the model that is changed would be one of the arguments the event is triggered with (http://backbonejs.org/docs/backbone.html#section-73). You can check what was changed by calling changedAttributes on the model (http://backbonejs.org/docs/backbone.html#section-77). However, reset does not necessarily seem to trigger update either.

    Add, reset and remove seems to be triggered in totally different cases than change for collection. You might be looking for "update" instead, which is triggered whenever the number of elements in the collection is changed: http://backbonejs.org/docs/backbone.html#section-118