Backbone.js - Remove all sub views

后端 未结 4 1219
一个人的身影
一个人的身影 2021-01-30 23:51

I have a top level PageView that will re-render itself whenever the route changes. I have many nested sub-views embedded into this PageView. If I was to re-render PageView, do

4条回答
  •  后悔当初
    2021-01-31 00:10

    Yes, you need to properly remove and unbind them:

    http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/

    The easy way to do this is to store an array of your sub-views in the parent view. Then in a close method on the parent view, loop through the array and call a close method on the child views:

    ParentView = Backbone.View.extend({
      initialize: function(){
        this.childViews = [];
      },
    
      render: {
        for (var i = 0; i < 10; i++){
          var childView = new ChildView();
          // do stuff with the child view
          this.childViews.push(childView);
        }
      },
    
      close: function(){
        this.remove();
        this.unbind();
        // handle other unbinding needs, here
        _.each(this.childViews, function(childView){
          if (childView.close){
            childView.close();
          }
        })
      }
    });
    

    Be sure to call the close method on the parent view when you are ready for it to be removed / replaced. This will ensure all of the children are cleaned up properly (assuming all of them have their own close method).

提交回复
热议问题