[英]Recreating a removed view in backbone js
骨干js中的View.remove()函数从DOM中删除视图本身的容器元素,防止重新创建已删除的视图。 知道如何处理这种情况
这是我的代码,
var AttributeView = Backbone.View.extend({
el: $("#attrs"),
template:_.template($('#attrs-template').html()),
initialize:function() {
},
render:function (eventName) {
$(this.el).html(this.template(this.model.toJSON()));
return this;
},
dispose:function(eventName){
this.unbind();
this.remove();
},
});
var attrView = new AttributeView();
....
attrView.dispose();
//Later on some event I do the below
attrView = new AttributeView()
attrView.render();
上面的最后两行不会重新创建视图,因为id =“attrs”的div不再存在。
首先,您不需要您的dispose
方法,标准remove
就足够了:
var attrView = new AttributeView();
//....
attrView.remove(); // <--------- Do this instead
//...
attrView = new AttributeView()
attrView.render();
其次,如果标准版本不能满足您的需要,您可以覆盖remove
。 默认实现只是删除this.el
并清理一些事件侦听器:
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
在你的情况,你要撤消一切render
确实,这意味着清理出里面的HTML this.el
并通过调用移除事件undelegateEvents
:
remove: function() {
this.undelegateEvents();
this.$el.empty();
this.stopListening();
return this;
},
然后你可以调用attrView.remove()
并将其attrView.remove()
(new AttributeView()).render()
将其恢复。
看看LayoutManager for Backbone Views,它理解当你删除一个视图(父 - 在包含意义而不是对象层次结构意义上)时,它的子视图也应该被删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.