问题描述
如果我将视图存储在 window.myView
变量中,则将其渲染,然后调用javascript控制台:
If I store view in window.myView
variable, render it, then call in javascript console:
$('#container').html('')
然后调用:
$('#container').html(window.myView.$el)
绑定事件将停止工作。
我很漂亮确实应该是这样,但是:
I'm pretty sure that is supposed to be so, but:
- 为什么它的工作原理?
- 为什么调用
myView.render()
不会丢失,如何重新呈现子视图w / o丢失事件绑定?
- why exactly it works this way?
- how to re-render subpart of view w/o losing event bindings?
- why calling
myView.render()
won't lose event bindings?
更新:
找到)
If you want to reuse your views you can remove them using the jQuery detach
method which keeps all the events and data bound though you have to watch out not to produce memory leaks this way. (jquery detach docs)
如果你想要走第一种方式,您可以随时使用Backbone.View delegateEvents
方法重新绑定Backbone事件。 ()
If you want to go the first way you can always rebind the Backbone events easily using the Backbone.View delegateEvents
method. (backbone doc)
ps。使用jQuery .empty()
而不是 .html('')
作为jQuery html也更干净,更优化方法始终调用空,首先在插入新的html之前先清除所有的事件和数据。也不会混合jquery和本机DOM innerHTML,因为它可能会产生内存泄漏,因为没有清理jQuery事件/数据
ps. it's also cleaner and more optimal to use jQuery .empty()
rather then .html('')
as jQuery html method always calls empty first to clean up all the events and data first before it inserts new html. Also never mix jquery and native DOM innerHTML as it might produce memory leaks cause of not cleaned up jQuery events/data
这篇关于为什么Backbone事件替换html不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!