Backbone.js 主干内存泄漏分离DOM
我在Chrome开发工具中使用profiler查看了分离的DOM树,在测试下面的代码时,我想我发现了内存泄漏。 工作流程如下所示: 加载页面 获取堆快照=>没有任何分离的dom树 单击filter event,它将过滤集合并再次呈现表 获取堆快照并与上一个快照进行比较=>有一个分离的树 调试完代码后,我发现问题出在下面一行Backbone.js 主干内存泄漏分离DOM,backbone.js,memory,Backbone.js,Memory,我在Chrome开发工具中使用profiler查看了分离的DOM树,在测试下面的代码时,我想我发现了内存泄漏。 工作流程如下所示: 加载页面 获取堆快照=>没有任何分离的dom树 单击filter event,它将过滤集合并再次呈现表 获取堆快照并与上一个快照进行比较=>有一个分离的树 调试完代码后,我发现问题出在下面一行 this.listenTo(this.model, "clearView", this.remove); //Line with problem 如果我删除了这一行
this.listenTo(this.model, "clearView", this.remove); //Line with problem
如果我删除了这一行,就没有分离的dom树,否则我就有分离的dom树。我是不是忘了解开什么东西了?任何帮助都将受到欢迎
谢谢
var Post = { Views: {} };
Post.Model = Backbone.Model.extend({
initialize: function() {
},
destroyView: function() {
}
});
Post.Collection = Backbone.Collection.extend({
model: Post.Model,
url: '/posts'
});
Post.Views.ModelView = Backbone.View.extend({
tagName: 'tr',
template: APP.Templates.PostModel,
initialize: function() {
this.listenTo(this.model, "clearView", this.remove); //Line with problem
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
remove: function() {
console.log("remove");
}
});
Post.Views.CollectionView = Backbone.View.extend({
template: APP.Templates.PostCollection,
events : {
"click .filter":"filter",
"click .delete":"clear"
},
initialize: function() {
this.toRenderModels = this.collection.models;
},
filter: function() {
this.toRenderModels = null;
this.toRenderModels = this.collection.where({title: 'Post 1'});
this.render();
},
clear: function() {
this.toDeleteModel = this.collection.at(0);
},
render: function() {
this.$el.empty();
this.$el.html(this.template());
_.each(this.toRenderModels, function(model) {
this.$('table').append(new Post.Views.ModelView({model: model}).render().el);
}, this);
this.toRenderModels = null;
return this;
}
});
标记为“有问题的行”的行应放置在视图的构造函数中 这里最重要的是调用remove方法,该方法删除元素并停止侦听事件
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
这是一个默认实现,您不必复制粘贴它
相关问题:同意您的回答,我将el.empty替换为removeViews实现,以便调用stopListening并解除事件绑定。