我已经close()为所有Backbone视图实现了一个简单的方法,当不需要/需要重置时,它会处理视图.
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() {
}
});
Run Code Online (Sandbox Code Playgroud)
现在,当我删除父视图时,我还想删除所有子视图.任何想法我怎么能这样做而不循环通过像这样的模型....
_(this.collection.models).each(function(item) {
item.close();
}, this);
Run Code Online (Sandbox Code Playgroud)
dir*_*ira 10
我认为在大多数情况下,您应该在视图层中保留视图删除,而不会影响您的模型.
例如,如果删除带有注释的视图,则应用程序中的另一个视图可能会显示一系列注释或某些统计信息,重置该集合也会影响这些视图.
所以我认为你应该在视图中保留所有内容(仅包括相关方法):
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();
});
}
});
Run Code Online (Sandbox Code Playgroud)