我有一个从网址填充的集合:
var PeopleCollection = Backbone.Collection.extend({
model: Person,
url: '/hr/xml-home-3a.php'
});
使用以下视图:
var PeopleView = Backbone.View.extend({
tagName: 'ul',
initialize: function () {
this.collection = new PeopleCollection();
this.collection.bind("reset", this.render, this);
this.collection.fetch();
},
render: function () {
this.collection.each(function (person) {
var personView = new PersonView({
model: person
});
this.$el.append(personView.render().el);
}, this);
return this;
}
});
我的问题是,我希望这个视图每5秒刷新一次,获得新鲜的Feed并使用这个新鲜的Feed重新显示。
当然,我可以用JS重新加载页面,但我想知道它是否可以在Backbone中完成。
答案 0 :(得分:3)
您可以尝试以下解决方案。可能还有其他解决方法,但我尝试了以下方法。这将重新呈现子视图并将实例保留在数组中。每隔5秒后刷新一次,它将关闭之前的子视图,并使用新的获取数据重新渲染它们。
var PeopleView = Backbone.View.extend({
tagName: 'ul',
initialize: function () {
this.collection = new PeopleCollection();
this.collection.bind("reset", this.render, this);
this.collection.fetch();
},
render: function () {
var self = this;
this.childViews = [];
this.collection.each(function (person) {
var personView = new PersonView({
model: person
});
this.childViews.push(personView);
this.$el.append(personView.render().el);
}, this);
setTimeout(function(){
self.reRender();
}, 5000);
return this;
},
reRender : function(){
var self = this;
this.collection.fetch({
success : function(){
_.each(self.childViews, function(view){
view.remove();
view.unbind();
});
self.childViews= [];
self.render();
}
});
}
});
答案 1 :(得分:1)
我会选择事件驱动的解决方案。例如,在刷新feed之后,你的集合应该触发一个事件,并且该事件应该由视图处理(例如,处理它应该调用'render'方法)。
此外,视图不应该刷新集合,它应该以完全相反的方式工作(集合应该刷新视图)。
答案 2 :(得分:1)
使用setTimeout进行新的集合提取是可以的。
但是,除非您确定集合中的所有模型在刷新时都已更改,否则重新渲染所有人物视图不是最佳解决方案。
更好的方法是将每个人视图的渲染方法绑定到其相应的集合模型中的更改(更改,添加,删除事件)。
如果您使用的是Backbone 1.0,则fetch会执行更新并默认触发添加,删除和更改事件。如果你是< 1.0你将使用fetch({update:true})来实现这一点。