jquery – 为什么Backbone事件替换html不起作用?

如果我在window.myView变量中存储视图,渲染它,然后调用 javascript控制台:
$('#container').html('')

然后调用

$('#container').html(window.myView.$el)

绑定事件将停止工作.

我确信这应该是这样,但是:

为什么这样做呢?
>如何重新呈现子视图w / o丢失事件绑定?
为什么调用myView.render()不会丢失事件绑定?

更新:

发现this文章.那是原因吗

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).

解决方法

jQuery空,html和remove事件正在清理所有jquery事件和数据绑定,以防止内存泄漏(您可以检查jQuery源代码的cleanData方法来找出更多 – 这是一个未记录的方法)

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事件/数据

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...