Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone events on model firing on collection (Double firing)

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.

like image 799
RandallB Avatar asked Mar 30 '12 22:03

RandallB


1 Answers

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/

like image 95
mu is too short Avatar answered Nov 14 '22 03:11

mu is too short