backbone js 中的 View.remove() 函数从 DOM 中删除 View 本身的容器元素,防止重新创建已删除的 View 。知道如何处理这种情况
这是我的代码,
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();
上面的最后两行没有重新创建 View ,因为带有 id="attrs"的 div 不再存在。
最佳答案
首先,您不需要dispose
方法,标准的remove
就足够了:
var attrView = new AttributeView();
//....
attrView.remove(); // <--------- Do this instead
//...
attrView = new AttributeView()
attrView.render();
其次,您可以覆盖 remove
如果标准版本不能满足您的需求。 default implementation简单地删除 this.el
并清理一些事件监听器:
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
在你的例子中,你想要撤消 render
所做的一切,这意味着清除 inside this.el
的 HTML 并删除通过调用事件 undelegateEvents
:
remove: function() {
this.undelegateEvents();
this.$el.empty();
this.stopListening();
return this;
},
然后您可以调用 attrView.remove()
并将其杀死,然后调用 (new AttributeView()).render()
将其恢复。
关于javascript - 在 backbone js 中重新创建已删除的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10966440/