【问题标题】:How to remove the events of child views and master views如何移除子视图和主视图的事件
【发布时间】:2014-01-24 04:35:30
【问题描述】:

我正在使用自定义事件创建主干视图。如果我删除主干视图,删除过程会取消订阅事件,或者我必须手动取消订阅事件。

同样,我创建了一个带有一些子视图的主视图。如果我删除主视图,我的所有子事件是否都会取消订阅,或者我必须取消订阅子事件并取消订阅主视图事件。

请建议我一种可以按正确顺序删除视图的方法,这样就不会发生内存泄漏。

【问题讨论】:

标签: backbone.js


【解决方案1】:

您需要为每个子视图调用remove() 方法,然后在您的视图上调用本机remove() 方法。原生移除将停止监听事件并从 DOM 中移除 $el

这是一个例子:

var View = Backbone.View.extend({

    initialize: function() {
        this.views.my_view_1 = new Backbone.View();
        this.views.my_view_2 = new Backbone.View();

        return this;
    },

    /*
     *  Remove child views and remove itself
     */
    remove: function() {
        // Remove the child views
        Object.keys(this.views).forEach(function(view_name) {
            if (is(this.views[view_name].remove, "function")) {
                this.views[view_name].remove();
            }
        }, this);

        // Call the native remove function.
        Backbone.View.prototype.remove.apply(this, arguments);

        // For old browsers we need convert arguments object to Array
        // Backbone.View.prototype.remove.apply(this, Array.prototype.slice.call(arguments));

        return this;
    }

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多