mza*_*fer 8 javascript 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();
Run Code Online (Sandbox Code Playgroud)
上面的最后两行不会重新创建视图,因为id ="attrs"的div不再存在.
mu *_*ort 21
首先,你不需要你的dispose方法,标准remove就足够了:
var attrView = new AttributeView();
//....
attrView.remove(); // <--------- Do this instead
//...
attrView = new AttributeView()
attrView.render();
Run Code Online (Sandbox Code Playgroud)
其次,remove如果标准版本不能满足您的需要,您可以覆盖.该默认实现简单地删除this.el和清理一些事件侦听器:
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您想要撤消所有render操作,这意味着清除内部 的HTML this.el并通过调用删除事件undelegateEvents:
remove: function() {
this.undelegateEvents();
this.$el.empty();
this.stopListening();
return this;
},
Run Code Online (Sandbox Code Playgroud)
然后你可以召唤attrView.remove()并杀掉它并(new AttributeView()).render()把它带回来.
演示:http://jsfiddle.net/ambiguous/Pu9a2/3/
| 归档时间: |
|
| 查看次数: |
4423 次 |
| 最近记录: |