Search code examples
backbone.js

Backbone.js - Remove all sub views


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 I need to remove/unbind all the nested sub-views along with the PageView or do I only need to remove/unbind the PageView? If I need to remove/unbind all the sub-views, what is the best way to go about doing this?


Solution

  • 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).