Backbone view DOM element removed

后端 未结 3 532
我在风中等你
我在风中等你 2021-02-06 16:39

I keep reading about the Backbone.js zombie (or memory leak) problem. Basically you have to unbind and remove the element from the DOM when you no longer need it to make sure al

相关标签:
3条回答
  • 2021-02-06 17:11

    In regard to losing the page1 element in your page, and therefore not being able to populate the item with HTML, I did the following.

    Instead of using:

    this.remove();
    

    ... which removes the element entirely, and then try to figure out how to add it back, I use jQuery's:

    $(this).empty;
    

    This empties all child elements, text, and data and event handlers. More info at: http://api.jquery.com/empty/

    In fact, I use all of the following, which may be overkill but we'll see:

    this.undelegateEvents();
    $(this).empty;
    this.unbind();
    

    Hope this is useful!

    0 讨论(0)
  • 2021-02-06 17:33

    As the article says, (yes, I've tried his methods before in my own projects), you have to find a way to remove your view's DOM element and unbind the events. There are, however, 2 types of events, 1) Backbone events, 2) the events that are bound to your DOM elements with jQuery.

    So instead of your:

    $(this.el).remove();
    $(this.el).unbind();
    

    Do this:

    this.remove();
    this.unbind();
    

    You are now removing Backbone events as well; and the this.remove on a view will call $(this.el).remove();.

    However, that is only how to remove a view and not leave zombies. You should consider his methods for showing a view to make this process more automatic. This is all in his article.

    0 讨论(0)
  • 2021-02-06 17:35

    Backbone development version(master) now exposes _removeElement()

     remove: function() {
          this._removeElement();
          this.stopListening();
          return this;
        },
    

    Remove this view’s element from the document and all event listeners attached to it. Exposed for subclasses using an alternative DOM manipulation API.

    _removeElement: function() {
          this.$el.remove();
        },
    

    http://backbonejs.org/docs/backbone.html

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