6

A Backbone app which I'm developing has a collection and a model, and associated views for each item.

https://gist.github.com/2255959

When I click on the PostView, unexpectedly, the event fires on the collection without any wiring.

I figured I'd need to bind an event to the model, then have that fire an event on the collection. Is that not the case? Does a collection automagically inherit events fired its child models?

I'm uncertain, but I think it has something to do with the nested views, and maybe the event is being bound on both places instead of just the inner el.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
RandallB
  • 5,415
  • 6
  • 34
  • 47

1 Answers1

15

From the fine manual:

Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience.

So yes, the collection listens to events on all of its models and forwards them.

For example, given a simple set up like this:

class M extends Backbone.Model

class C extends Backbone.Collection
    model: M

c = new C
c.on('change', (model, opts) -> console.log('Change on collection'))

Doing c.first().set(...) will trigger the event handler.

Demo: http://jsfiddle.net/ambiguous/wwjnK/

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • 1
    Do you know if this can be applied inversely? So I trigger an event in a collection and then propagate this event to each model object in the collection? – dombesz Jul 03 '12 at 13:06
  • 1
    @dombesz: I think you'd have to do that by hand but the Underscore methods mixed I to collections should make it a quick one liner. – mu is too short Jul 03 '12 at 17:49
  • I just found out that if I trigger an event on a model, the same event will be triggered on the collection too. – dombesz Jul 04 '12 at 07:49
  • @dombesz: ["Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience."](http://backbonejs.org/#Collection) but not the other way around. – mu is too short Jul 04 '12 at 08:08