Backbone.js - Remove all sub views

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

    Instead of keeping an array of children view, could iterate through all the properties of your view and see which ones are an instance of Backbone.View; you will need to make sure to set a property for each child view in your parent view.

    In the example below, the child views are set to properties of the parent view. I'm not sure what the performance hit will be looping through all the properties, however, it may be easier than keeping track of a separate data structure for the child views.

    Example:

    var ContextView = Backbone.View.extend({
        initialize: function() {
          // views render themselves via their initialize methods
          this.titlebar = new TitlebarView({el: $("#titlebar")});       
          this.toolbar = new ToolbarView({el: $("#toolbar")});
          this.content = new ContentView({el: $("#content")});
        },
        removeChildViews: function() {      
            for(var prop in this){
                if (this[prop] instanceof Backbone.View) {
                    console.log("This is a view: "+ prop + ' in ' + this[prop]);    
                }
            }
        }, 
        render: function() {
            this.$el.html(this.el);
        }
      });
    

提交回复
热议问题