Thomas Thomas - 2 years ago 72
Javascript Question

Backbone.js: Collection's "change" event isn't firing

I have a pretty simple collection, but I can't seem to bind to it's change event. In Chrome's console, I'm running:

var c = new AwesomeCollection();
c.bind("change", function(){
console.log('Collection has changed.');

c.add({testModel: "Test"}); // Shouldn't this trigger the above log statement?

Since this is one of those things that can be difficult to track down, I doubt anybody knows off the top of their head what's going on (if so, great!). So, I'm asking two questions:

  1. Should the above code work as anticipated?

  2. If so, do you have any suggestions on how to track down where this would fail?


Answer Source

The change event is only fired when one of the collections' models are modified. When a model is added to the collection the add event is fired.
See Backbone.js' Collection Documentation:

You can to bind "change" events to be notified when any model in the collection has been modified, listen for "add" and "remove" events[...]

To listen for when an add occurs modify your code to be

var c = new AwesomeCollection();
c.bind("add", function(){
  console.log('Collection has changed.');

c.add({testModel: "Test"}); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download