我通常会清除视图,有时会重用模型。如果保留模型,则确保视图已被解除分配可能很麻烦。如果没有正确解绑,模型可能会保留对视图的引用。
从Backbone ~0.9.9开始,使用view.listenTo()而不是model.on()来绑定模型,可以通过控制反转(视图控制绑定而不是模型)更轻松地进行清理。如果使用view.listenTo()进行绑定,则调用view.stopListening()或view.remove()将删除所有绑定。类似于调用model.off(null, null, this)。
我喜欢通过扩展视图并添加一个close函数来清除视图中的子视图。子视图必须由父级属性引用,或者它们必须添加到名为childViews[]的父级数组中。
这是我使用的close函数..
Backbone.View.prototype.close = function () {
if (this.closing) {
this.closing();
}
if (this.childViews) {
_.each(this.childViews, function (child) {
child.close();
});
}
for (var prop in this) {
if (this[prop] instanceof Backbone.View) {
this[prop].close();
}
}
this.unbind();
this.remove();
}
然后按照以下方式声明一个视图..
views.TeamView = Backbone.View.extend({
initialize: function () {
this.childViews = [];
this.listenTo(this.collection, "add", this.add);
this.listenTo(this.collection, "reset", this.reset);
this.editView = new views.EditView({ model: this.model.edits });
$('#edit', this.el).html(this.editView.render().el);
},
add: function (member) {
var memberView = new views.MemberView({ model: member });
this.childViews.push(memberView);
var item = memberView.render().el;
this.$el.append(item);
},
reset: function () {
_.each(this.childViews, function (child) {
child.close();
});
this.childViews = [];
},
render: function () {
this.$el.empty();
_.each(this.collection.models, function (member) {
this.add(member);
}, this);
return this;
}
closing: function () {
}
});