如何在不解除绑定事件的情况下分离然后重新附加 Backbone.View?
我有一个由嵌套子视图组成的主干系统,我偶尔需要在其中执行以下操作。
- 从 DOM 中分离子视图
- 从头开始重新渲染父视图(从模板)
- 在正确的位置重新附加子视图 来
我通过调用类似 $(parent.el).html(...)
然后调用 $(parent.el).append(child.el)
做到这一点我经常看到这种技术会导致子进程的事件处理程序丢失。所以我尝试了很多方法,但到目前为止都没有效果。
- 首先使用
$.detach()
分离 child.el - 克隆 child.el 节点并重新附加克隆
- 重新附加后再次调用 child.delegateEvents()
唯一对我有用的是完全重建子节点从头开始查看。有人有什么想法吗?重新连接现有节点会更加高效。
谢谢!
I have a Backbone system consisting of nested sub-views in which I occasionally need to do the following.
- Detach a child view from the DOM
- Re-render the parent view from scratch (from a template)
- Re-attach the child view at the correct
place
I do this by calling something like $(parent.el).html(...)
and then $(parent.el).append(child.el)
What I have always seen with this technique is that the event handlers on the child are lost. So I have tried a number of things, none of which have worked so far.
- Detaching the child.el first with
$.detach()
- Cloning the child.el node and reattaching the clone
- Calling child.delegateEvents() again after reattaching
The only thing that works for me is completely rebuilding the child view from scratch. Does anyone have any ideas? Reattaching the existing node would be much more efficient.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我刚刚遇到了类似的问题。这似乎对我有用:
我仍然不确定为什么事件侦听器消失,尽管当我查看 Chrome 开发人员工具窗口时我可以确认它们实际上已经消失了。这很奇怪,因为 Roatin Marth 有一个示例(http://jsfiddle.net/Xcrhb/1),其中不会出现这个问题。
I just had a similar problem. This seemed to work for me:
I'm still not exactly sure why the event listeners disappear, though I can confirm they are actually gone when I look in the Chrome developer tools window. It's strange, because Roatin Marth has an example (http://jsfiddle.net/Xcrhb/1) where this problem doesn't occur.
我也这么做。
I do exactly the same.
你想要做的事情对于 Backbone 来说似乎是 hack 式的。您最好通过设置事件委托和重新渲染视图来使用本机功能,而不是分离、克隆、更改和重新附加。这样做并不会提高任何性能。
如果您解释了为什么需要这样做以及为什么本机 Backbone 做事方式不适合您,那么提供帮助会容易得多。
What you're trying to do seems to be hack-ish to Backbone. You would be better off using native functionality by setting up event delegation and re-rendering views instead of detaching, cloning, altering and re-attaching. You don't get any performance increase by doing it.
It would be much easier to help if you explained why you need to do it this way and why native Backbone way of doing things does not work for you.