Search code examples
javascriptbackbone.jsbackbone-eventsbackbone.js-collections

Backbone binding to add event on collection


I have problem with backbone collections. I trying to listen all events on collection:

  this.collection.on('all', function(ev) {
    console.log(ev);
  });

And collection trigger event only when I create record like this:

  this.collection.create({name: 'aloha'});

But not when I create model instance directly:

  var room = new Room({name: 'hello'}); // this code not trigger any events on collection
  room.save();

I am new to Backbone, but I think that second code should trigger event. Can somebody help me? Thanks!


Solution

  • The event is not triggered on the collection, because the room model is not associated (i.e. has not been added) to this.collection.

    Assuming you have defined your model and collection similar to:

    var Room = Backbone.Model.extend();
    
    var Rooms = Backbone.Collection.extend({
      model:Room
    });
    
    var rooms = new Rooms();
    
    rooms.on('all',function(eventName) {
      console.log(eventName);
    });
    

    For your code to work as expected you would have to add the room model to the rooms collection such as:

    var room = new Room({'name':'hello'});
    
    // This will trigger the add event on the collection
    rooms.add(room);
    
    // save the model
    room.save();
    

    The following is short-hand for the above code block:

    var room = rooms.create({'name':'hello'});
    

    Here is a FIDDLE showing the behavior.