重新渲染视图 - 骨干 [英] Re-render the view - backbone
问题描述
我是新来的骨干,我试图重新渲染视图的内容。我已经竖起了code中的jsfiddle ...
I'm new to backbone and i'm trying to re-render the contents of a view. I've put up the code in jsfiddle ...
因此,当用户点击重新渲染如何删除的内容在DOM中,仅显示新项目?
So when user clicks re-render how can i remove the contents in the dom and show only the new items ?
推荐答案
做最安全的做法是保持跟踪你的 QuestionView
实例你的 APPVIEW
。然后,你可以调用删除
每个 QuestionView
添加新的之前; 删除
方法是:
The safest thing to do is to keep track of your QuestionView
instances inside your AppView
. Then you can call remove
on each QuestionView
before adding the new ones; the remove
method is a:
去除从DOM的观点方便的功能。相当于调用 $(view.el)一个.remove()
;
Convenience function for removing the view from the DOM. Equivalent to calling
$(view.el).remove()
;
意见应该提供自己的删除
实施非DOM事件,因此prevent僵尸解除绑定。默认只会删除该视图的报
从DOM,但如果你从一开始就这样做,事情会继续很好地工作时,你的code不可避免地发生变化。
Views should provide their own remove
implementation to unbind from non-DOM events and thus prevent zombies. The default simply removes the view's el
from the DOM but if you do it right from the beginning, things will keep working nicely when your code inevitably changes.
首先调整 QuestionView
有一个删除
方法来删除你已经绑定到模型的事件:
First adjust your QuestionView
to have a remove
method to remove the event you've bound to the model:
var QuestionView = Backbone.View.extend({
//...
remove: function() {
this.model.off('change', this.render);
this.$el.remove();
}
});
然后,你需要一对夫妇的调整 APPVIEW
来跟踪你的 QuestionView
取值:
var AppView = Backbone.View.extend({
//...
initialize: function() {
//...
this.sub_views = [ ];
//...
},
//...
addOne: function(question) {
var view = new QuestionView({
model: question
});
this.sub_views.push(view); // <----------------------- Add this
this.$("#question-list").append(view.render().el);
},
addAll: function() {
for(var i = 0; i < this.sub_views.length; ++i) // <--- And these three lines
this.sub_views[i].remove();
this.sub_views = [ ];
Questions.each(this.addOne);
}
演示: http://jsfiddle.net/ambiguous/FF9eG/
我也更新了code使用 在
和 关闭
而不是绑定
和取消绑定
来匹配新的风格。主干的较新版本也有 $(this.el)
中的 这一点。$埃尔
所以我已经更新了code使用的为好。
I've also updated your code to use on
and off
instead of bind
and unbind
to match the new style. Newer versions of Backbone also have a cached version of $(this.el)
in this.$el
so I've updated the code to use that as well.
这篇关于重新渲染视图 - 骨干的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!