Backbone events on model firing on collection (Double firing)

不打扰是莪最后的温柔 提交于 2019-12-06 02:09:34

问题


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:


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/



来源:https://stackoverflow.com/questions/9951222/backbone-events-on-model-firing-on-collection-double-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!