在您的示例中,您没有将视图的el
进入 DOM,因此没有任何内容引用该视图,那么它将被垃圾收集器收集。
确保视图不再绑定到某些东西的一件好事是call .remove() on it。它将删除:
- 观点
el
从 DOM 中,
- jQuery DOM 事件
- Backbone 事件监听器。
骨干.remove source:
// Remove this view by taking the element out of the DOM, and removing any
// applicable Backbone.Events listeners.
remove: function() {
this._removeElement();
this.stopListening();
return this;
},
// Remove this view's element from the document and all event listeners
// attached to it. Exposed for subclasses using an alternative DOM
// manipulation API.
_removeElement: function() {
this.$el.remove();
},
正如所提到的mu 太短了在评论中(以及我自己在几乎所有其他答案中),你应该始终favor listenTo over on or bind以避免内存泄漏并简化解除绑定事件。
渲染嵌套在父视图中的子视图时,一个好的做法是保留子视图的数组以供以后调用.remove()
在他们每个人身上。
一个简单的列表视图可能如下所示:
var ListView = Backbone.View.extend({
initialize: function() {
// Make an array available to keep all the child views
this.childViews = [];
},
addOne: function(model) {
var view = new Backbone.View({ model: model });
// as you create new views, keep a reference into the array.
this.childViews.push(view);
this.$el.append(view.render().el);
},
renderList: function() {
// replace the view content completely with the template
this.$el.html(this.templates());
// then cleanup
this.cleanup();
// then render child views
this.collection.each(this.addOne, this);
return this;
},
cleanup: function() {
// quick way to call remove on all views of an array
_.invoke(this.childViews, 'remove');
// empty the array
this.childViews = [];
},
});
尽管如果其他对象正在监听它,它不会被收集并且可能是泄漏。跟踪引用并在不再需要时将其全部删除非常重要。