我遇到了 DOM 元素在被删除后留在内存中的问题。我已经设置了一个如下所示的示例。注意我正在使用主干布局管理器插件来管理我的视图(以及 jQuery)。
在删除列表中的一项之前和之后,我在 Chrome 中做了一个堆快照,并比较了两者:
如您所见,LI 元素仍在内存中。
删除视图时,主干布局管理器会调用 view.unbind() 和 view.stopListening()。
下面是示例代码。
ListOfViewsToDelete.js
var TestModel = Backbone.Model.extend({
});
var TestCollection = Backbone.Collection.extend({
model: TestModel,
});
var ViewToDelete = Backbone.View.extend({
template: "ViewToDelete",
tagName: "li",
events: {
"click .delete-button": "deleteItem"
},
deleteItem: function() {
this.$el.trigger('remove-item', [this.model.id]);
}
});
var ListOfViewsToDelete = Backbone.View.extend({
template: "ListOfViewsToDelete",
initialize: function() {
this.collection = new TestCollection();
for (var i = 0; i < 5; i++) {
this.collection.add(new TestModel({id: i}));
}
this.listenTo(this.collection, 'all', this.render);
},
events: {
"remove-item": "removeItemFromCollection"
},
beforeRender: function() {
this.collection.each(function(testModel) {
this.insertView("ul", new ViewToDelete({
model: testModel
}));
}, this);
},
removeItemFromCollection: function(event, model) {
this.collection.remove(model);
}
});
路由器.js
app.useLayout("MainLayout").setViews({
"#main": new ListOfViewsToDelete()
}).render();
ListOfViewsToDelete.html
<ul>
</ul>
ViewToDelete.html
View to delete
<button class="delete-button">x</button>