收集时模型触发的主干事件(双重触发) [英] Backbone events on model firing on collection (Double firing)
问题描述
我正在开发的一个 Backbone 应用程序有一个集合和一个模型,以及每个项目的关联视图.
https://gist.github.com/2255959
当我点击 PostView 时,意外地,事件在没有任何连接的情况下在集合上触发.
我想我需要将一个事件绑定到模型,然后让它在集合上触发一个事件.不是这样吗?集合是否会自动继承触发其子模型的事件?
我不确定,但我认为它与嵌套视图有关,也许事件被绑定在两个地方,而不仅仅是内部 el
.
出自精细手册:p><块引用>
为方便起见,在集合中的模型上触发的任何事件也将直接在集合上触发.
所以是的,集合会监听其所有模型上的事件并转发它们.
例如,给定这样一个简单的设置:
M 类扩展 Backbone.ModelC 类扩展 Backbone.Collection型号:Mc = 新 Cc.on('change', (model, opts) -> console.log('Change on collection'))
执行 c.first().set(...)
将触发事件处理程序.
演示:http://jsfiddle.net/ambiguous/wwjnK/
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
.
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/
这篇关于收集时模型触发的主干事件(双重触发)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!