在Backbone.js的delegateEvents [英] delegateEvents in backbone.js
问题描述
任何人都可以请解释我什么delegateEvents在Backbone.js的呢? 没有帮助我理解的文档。
我的详细使用情况是:
我有一个内部景观Y.他们的工作大的主视图X,但如果我去主视图Z和再回去X(重用,而不是重新创建),然后连接于Y子元素的事件迷路。 delegateEvents解决了这个,但
我想知道为什么。
从本质上讲,当你调用一个.remove()
这是代理了jQuery的remove 功能,从而消除从DOM元素,以及从该被绑定到该元素的事件散列所有相关联的事件。对>
骨干View元素还包含 .el
,但在DOM中重新插入,jQuery的元素已经失去了它的所有绑定的监听器。
有几个解决方案:
-
彻底摧毁视图元素,包括取消绑定新的摧毁方法的所有模型/控制器事件(目前仅在github上,它将在骨干的下一个版本中添加)和回来时(而不仅仅是缓存和重新渲染)创建一个新的观点 - 我的preferred法
-
创建一个方法(或扩展remove)使用jQuery的 detatch 这显然不为删除不失相同事件绑定 - 没有做过,但好像它的工作
-
呼叫
.delegateEvents()
在每一个渲染 - 你目前在做什么,现在
希望这有助于。
Can anyone please explain me what delegateEvents in backbone.js does? The documentation did not help me to understand.
My exact use case is:
I have a main view X with an inner view Y. They work great, but if I go to main view Z and then go back to X (reusing, not recreating) then events attached to Y child elements get lost. delegateEvents solves this but I want to understand why.
Essentially, when you call .remove()
it is a proxy to the jQuery remove function, which removes the element from the DOM, as well as all associated events from the event hash that were bound to the element.
Backbone's View element still contains the .el
, but upon re-inserting in the DOM, the jQuery element has lost all of it's bound listeners.
There are a few solutions:
Completely destroy the view element, including unbinding all model/controller events with the new destroy method (currently only in the github, it will be added in the next release of Backbone) and create a new view when coming back (rather than just caching and re-rendering) - my preferred method
Create a method (or extend remove) to use jQuery's detatch which apparently does the same as remove without losing the event bindings - haven't done it but seems like it would work
Call
.delegateEvents()
in every render - what you're currently doing now
Hope this helps.
这篇关于在Backbone.js的delegateEvents的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!