$('#container').html('')
然后调用:
$('#container').html(window.myView.$el)
绑定事件将停止工作.
我确信这应该是这样,但是:
为什么这样做呢?
>如何重新呈现子视图w / o丢失事件绑定?
为什么调用myView.render()不会丢失事件绑定?
更新:
Make sure jQuery isn’t unloading your events when you don’t want it to
If you are building an app where you create views on the fly and attach/remove them to the dom,you may have a problem. Everytime you remove a view from the dom,jQuery unloads all the events. So you can’t have a reference to a view and remove it from the dom and then re-attach it later. All your events would have been unloaded. If you wanna keep the views around,a better idea is to hide them using display:none. However,you should not abuse this and recycle views that you are not going to use for a while (and prevent memory leaks).
解决方法
view.render()不会删除事件,因为Backbone视图事件是使用事件委派绑定的,并且绑定到视图的el,而不是直接绑定到视图中的元素.
如果要重用您的视图,您可以使用jQuery detach方法删除它们,该方法可以保持所有事件和数据的约束,但必须注意不要以这种方式产生内存泄漏. (jquery detach docs)
如果您想要第一种方式,您可以使用Backbone.View delegateEvents方法轻松地重新绑定Backbone事件. (backbone doc)
PS.使用jQuery .empty()而不是.html(”),jQuery html方法始终调用空,首先清除所有事件和数据,然后再插入新的html,这样也就更为清晰,更优化.也不要混合jquery和本机DOM innerHTML,因为它可能会产生内存泄漏,因为没有清理jQuery事件/数据