内存泄漏删除骨干视图

时间:2015-11-15 17:47:00

标签: jquery backbone.js

执行以下代码时,不会完全删除Collection View。 currentView.remove();currentView.unbind();不会删除&取消绑定模型视图中的整个视图 。删除集合视图+模型视图需要做什么? (重置是没有选择)

var Coll_Item = .. //contains collection within models

var currentView = new DiagnoseApp.Views.Coll_Item({collection: Coll_Item}); 
currentView.remove();
currentView.unbind();

(我使用google-chrome进行堆快照,每当代码执行时,堆都会增长。)

收藏视图:

DiagnoseApp.Views.Coll_Item = Backbone.View.extend({
    initialize: function(){
        this.collection;
    },
    render: function(){
        this.addAll();
    },
    addAll: function(){
            this.$el.html($('<table id="whatever" />'));
            this.collection.each(this.addOne, this);             
    },
    addOne: function(Param){
            var tbodyView = new DiagnoseApp.Views.item({model: Param});
            this.$el.find('#whatever').append(tbodyView.el);
    }
});

模型视图:

DiagnoseApp.Views.item   = Backbone.View.extend({
    newTemplate: _.template($('#item-template1').html()),
    initialize: function () {
        this.render();
        this.model.on('change', this.render, this);
    },
    render: function () {
         this.$el.html(this.newTemplate( this.model.toJSON() ));
    },
    events: {
        'blur .edit' :      'editParam',
        'keypress .edit' :  'updateOnEnter'
    },
    updateOnEnter: function (e){
        if (e.which == 13){
          this.editParam();
        }
    },
    editParam: function(){
         var newValue = this.input.val().trim();
         this.model.set('val', newValue);
    }
}); 

1 个答案:

答案 0 :(得分:2)

Dominic有正确的答案,但如果您需要更多详细信息:在您的代码中声明

this.model.on('change', this.render, this);

使模型存储对视图的引用。只要该模型存在,该引用仍将存在,并且JavaScript将不得不保留视图的副本,以防模型试图对其执行某些操作。

相反,如果您按照Dominic的建议更改代码:

this.listenTo(this.model, 'change', this.render);

然后模型将不再保留对视图的引用。在这种情况下,删除视图是安全的,并且JavaScript引擎将在删除视图时释放内存。