Why Backbone events on replacing html does not work?

前端 未结 1 708
小蘑菇
小蘑菇 2021-02-05 15:11

If I store view in window.myView variable, render it, then call in javascript console:

$(\'#container\').html(\'\')

and then call:

相关标签:
1条回答
  • 2021-02-05 15:57

    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

    0 讨论(0)
提交回复
热议问题