[英]Do i have to delete unused views on backbone.js
var Home = Backbone.View.extend({
template: _.template($('#home-template').html()),
initialize: function (params) {
this.collection = new BlogList();
this.listenTo(this.collection, "add", this.renderBlog);
this.listenTo(this.collection, "reset", this.render);
},
render: function () {
this.$el.html(this.template({hasPrevious: this.collection.hasPrevious()}));
this.collection.each(function(item) {
this.renderBlog(item);
}, this);
return this;
},
renderBlog: function(item) {
this.$('#blog-list-container').append((new BlogPreView({ model: item })).render().el);
},
BlogPreView是Backbone.View新的BlogPreView被实例化很多次。 我需要删除旧的吗?
在这个特定的示例中,如何删除belish.view?如何删除?
您应该在视图上调用remove
将其删除。 这将删除DOM中的el
并调用stopListening
撤消您进行的所有listenTo
调用。 如果还有其他要清除的内容,则应重写remove
来清除这些“其他内容”,然后调用标准remove
。
在您的情况下,您有子视图,因此您应该跟踪它们:
renderBlog: function(item) {
var v = new BlogPreView({ model: item });
this.previews.push(v); // Initialize this in `initialize` of course.
this.$('#blog-list-container').append(v.render().el);
}
然后清理它们,然后重新渲染或删除:
removePreviews: function() {
_(this.previews).invoke('remove');
this.previews = [ ];
},
render: function() {
this.removePreviews();
// what you have now goes here...
},
remove: function() {
this.removePreviews();
return Backbone.View.prototype.remove.apply(this);
}
你经常可以逃脱不调用remove
,但一旦你发现你确实需要它,它可以是一个巨大的麻烦来改造你的代码remove
正确的事情。 但是,如果您一直都在调用remove
,正确跟踪子视图,并根据需要覆盖remove
,那么以后再进行令人不快的改造就不会卡住。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.