骨干网中的垃圾收集

Garbage collection in Backbone

本文关键字:骨干网      更新时间:2023-09-26

*更新-为其中一个视图添加了示例代码*

这个话题已经讨论过很多次了,我也听取了很多关于这个话题的建议,但我仍然没有任何运气。

我的应用程序是基于选项卡的,即用户在全局搜索框中搜索实体,并在选择实体时生成视图/模型,视图在新选项卡下呈现。用户可以通过重复上述过程打开多个选项卡。

我面临的问题是,每次打开一个新标签页,我都可以看到浏览器内存消耗增加了大约6 MB(获取的数据&每个选项卡显示的最大值为60kb)。

不仅如此,但当我关闭一个选项卡,我可以看到我的自定义关闭函数(下面复制)被调用的每个视图下的选项卡,但不知何故浏览器内存没有下降。这对我来说意味着垃圾收集不工作或视图/模型没有被正确清理。

任何帮助都将不胜感激。

define([
    "hbs!modules/applications/templates/applications",
    "vent"
],
function (tpl, vent) {
    var View = Backbone.Marionette.ItemView.extend({
        className: 'modApplications',
        template: {
            type: 'handlebars',
            template: tpl
        },
        refresh: function(){
            self.$('.body-of-table').css('visibility', 'hidden');
            self.$('.application-panel .spinnerDiv').addClass('loading');
            this.model.fetch().always(function(){
                self.$('.application-panel .spinnerDiv').removeClass('loading');
            });
        },
        initialize: function(){
            this.model.on('change', this.render, this);
            vent.bindTo(vent, 'updateApplications', this.refresh, this);
        },
        onShow: function(){
            var self = this;
            this.$el.on('click', '.action-refresh', function(e) {
                self.refresh();
                e.preventDefault();
            });
        },
        close: function() {
            _.each(this.bindings, function (binding) {
                binding.model.unbind(binding.ev, binding.callback);
            });
            this.bindings = [];
            this.unbind();
            this.off();
            this.model.off('change');
            this.model.unbind('change', this.render, this);
            this.remove();
            delete this.$el;
            delete this.el;
            if(console) console.log("kill : view.applications");
        }
    });
    return View;
});

发现问题&修复。

问题是,我正在使用一个全局木偶。EventAggregator用于所有新标签。这被用作标签内各个部分之间的通信手段。现在,当一个选项卡关闭时,main.js文件仍然持有对全局vent的引用,因为其他选项卡仍在使用它。这是对关闭选项卡的引用仍然保持的地方,因此视图/模型没有被gc。

为了解决这个问题,我为每个选项卡创建了一个单独的vent,并使用该vent对象来触发该选项卡中的任何事件。在选项卡关闭操作上,我unbindAll事件并为要关闭的选项卡的vent分配一个空引用。