微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/jquery/180211.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐