我已经实现了一个简单的 close()
所有主干 View 的方法,这些 View 在不需要/需要重置时处理 View 。
Backbone.View.prototype.close = function() {
if (this.onClose) {
this.onClose();
}
this.remove();
this.unbind();
};
NewView = Backbone.View.extend({
el: '#List ul',
initialize: function() {},
render: function() {
_(this.collection.models).each(function(item) {
this.renderChildren(item);
}, this);
},
renderChildren: function(item) {
var itemView = new NewChildView({ model: item });
$(this.el).prepend(itemView.render());
},
onClose: function() {
this.collection.reset();
// I want to remove the child views as well
}
});
NewChildView = Backbone.View.extend({
tagName: 'li',
render: function() {
}
});
现在,当我删除父 View 时,我还想删除这里的所有 subview 。任何想法如何在不循环这样的模型的情况下做到这一点....
_(this.collection.models).each(function(item) {
item.close();
}, this);
最佳答案
我认为在大多数情况下,您应该在 View 层中保留 View 移除,而不会影响您的模型。
例如,如果你删除一个带有评论的 View ,你应用中的另一个 View 可能会显示一些评论或一些统计信息,重置集合也会影响这些 View 。
所以我认为您应该将其全部保留在 View 中(仅包括相关方法):
NewView = Backbone.View.extend({
initialize: function() {
this.childViews = [];
},
renderChildren: function(item) {
var itemView = new NewChildView({ model: item });
$(this.el).prepend(itemView.render());
this.childViews.push(itemView);
},
onClose: function() {
_(this.childViews).each(function(view) {
view.close();
});
}
});
关于Backbone.js:如何对父 View 和 subview 执行垃圾收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8006458/