问题描述
如果我存储视图 window.myView
变量,渲染它,然后在JavaScript控制台呼叫:
$('#集装箱')。HTML('')
然后调用:
$('#集装箱')。HTML(window.myView。$ EL)
绑定事件将停止工作。
我是pretty肯定应该是这样,但:
- 到底为什么是这样工作的?
- 如何重新渲染视图分部W / O丢失事件绑定?
- 为什么叫
myView.render()
不会丢失事件绑定?
更新:
一文。那是什么原因呢?
jQuery empty
, html
and remove
events are cleaning up all the jquery event and data bindings to prevent memory leaks (you can check jQuery source code for cleanData
method to figure out more - it's an undocumented method)
view.render()
doesn't remove the events because Backbone view events are bound using event delegation and are bound to the view's el
rather then directly to the elements in the view.
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)
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. 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
这篇关于为什么在更换HTML不起作用骨干事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!