6
votes

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.

1

1 Answers

15
votes

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/