Backbone.js - Remove all sub views

后端 未结 4 1426
一个人的身影
一个人的身影 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:22

    A simple and modular class you might find useful.

    ContainerView = Backbone.View.extend({
      initialize: function() {
        this.children = [];
      },
      remove: function() {
        Backbone.View.prototype.remove.apply(this, arguments);
        this.removeAllChildren();
      },
      removeAllChildren: function() {
        _.each(this.children, function(view) { view.remove(); });
        this.children = [];
      },
      appendAllChildren: function() {
        _.each(this.children, function(view) { this.$el.append(view.render().$el); }, this);
      }
    });
    

    usage:

    MyView = ContainerView.extend({
      render: function() {
        this.removeAllChildren();
        this.$el.empty();
    
        // For each child view...
        // this.children.push(new SomeControl(...));
    
        this.appendAllChildren();
        return this;
      }
    });
    

提交回复
热议问题