Pattern to manage views in backbone

后端 未结 4 1644
误落风尘
误落风尘 2021-01-30 09:34

Coming from GWT, Backbone seems to miss a built-in solution on how to handle the life-cycle of a view. In GWT, every activity, which is more or less the equivalent to a View in

4条回答
  •  旧时难觅i
    2021-01-30 10:00

    I'm using a custom BaseView, which extends Backbone's remove method:

    app.BaseView = Backbone.View.extend({
    
        views: [], // array to keep a ref of child-views for proper disposal later on
    
        remove: function() {
    
            // dispose any sub-views
            _.each(this.views || [], function(view) {
                view.remove();
            });
    
            // if the inheriting class defines a custom on-remove method, call it!
            _.isFunction(this.onRemove) && this.onRemove();
    
            // unbind all events from this view
            this.off();
    
            // finally, call Backbone's default remove method to
            // remove the view from the DOM
            Backbone.View.prototype.remove.call(this);
        }
    }
    

    There's still a catch: models and collections need to be disposed by hand, because you don't know if it's used by other views too.

提交回复
热议问题