2

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!

mu is too short
  • 426,620
  • 70
  • 833
  • 800
ssbb
  • 1,965
  • 2
  • 14
  • 26
  • 1
    here is example and search specific part Model Collections http://www.sinbadsoft.com/blog/backbone-js-by-example-part-1/ – F.C.Hsiao Dec 23 '13 at 02:23

1 Answers1

3

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.

fbynite
  • 2,651
  • 1
  • 21
  • 25
  • Many thanks for the clarification. Just did not realize that the model is not associated with the collection, only in reverse. Just expect that it works on the similarity to ActiveRecord. Thank you again! – ssbb Dec 23 '13 at 07:42