我有一个顶级的PageView,只要路由改变,它就会重新渲染自己。我在这个PageView中嵌入了许多嵌套的子视图。如果我要重新呈现PageView,我是需要移除/解除绑定所有嵌套的子视图以及PageView,还是只需要移除/解除绑定PageView?如果我需要移除/解绑所有的子视图,最好的方法是什么?
发布于 2012-03-02 10:02:50
可以,您需要正确移除并解绑它们:
要做到这一点,最简单的方法是在父视图中存储子视图数组。然后在父视图上的close方法中,遍历数组并调用子视图上的close方法:
ParentView = Backbone.View.extend({
initialize: function(){
this.childViews = [];
},
render: {
for (var i = 0; i < 10; i++){
var childView = new ChildView();
// do stuff with the child view
this.childViews.push(childView);
}
},
close: function(){
this.remove();
this.unbind();
// handle other unbinding needs, here
_.each(this.childViews, function(childView){
if (childView.close){
childView.close();
}
})
}
});当您准备好移除/替换父视图时,一定要调用父视图上的close方法。这将确保所有的子对象都被正确清理(假设所有的子对象都有自己的close方法)。
发布于 2013-02-07 02:10:00
一个简单且模块化的类,你可能会发现它很有用。
ContainerView = Backbone.View.extend({
initialize: function() {
this.children = [];
},
remove: function() {
Backbone.View.prototype.remove.apply(this, arguments);
this.removeAllChildren();
},
removeAllChildren: function() {
_.each(this.children, function(view) { view.remove(); });
this.children = [];
},
appendAllChildren: function() {
_.each(this.children, function(view) { this.$el.append(view.render().$el); }, this);
}
});用法:
MyView = ContainerView.extend({
render: function() {
this.removeAllChildren();
this.$el.empty();
// For each child view...
// this.children.push(new SomeControl(...));
this.appendAllChildren();
return this;
}
});发布于 2013-01-17 06:23:22
您可以遍历视图的所有属性并查看哪些属性是Backbone.View的实例,而不是保留子视图的数组;您需要确保在父视图中为每个子视图设置一个属性。
在下面的示例中,子视图被设置为父视图的属性。我不确定循环遍历所有属性会对性能造成什么影响,但是,它可能比跟踪子视图的单独数据结构更容易。
示例:
var ContextView = Backbone.View.extend({
initialize: function() {
// views render themselves via their initialize methods
this.titlebar = new TitlebarView({el: $("#titlebar")});
this.toolbar = new ToolbarView({el: $("#toolbar")});
this.content = new ContentView({el: $("#content")});
},
removeChildViews: function() {
for(var prop in this){
if (this[prop] instanceof Backbone.View) {
console.log("This is a view: "+ prop + ' in ' + this[prop]);
}
}
},
render: function() {
this.$el.html(this.el);
}
});https://stackoverflow.com/questions/9522845
复制相似问题