我创建了一个骨干模型,它从服务器获取json。但是,我想在特定的时间间隔内使用新数据更新视图,而不是每次服务器发送数据时。我应该用什么来每隔n毫秒更新主干视图?我有上面的代码。
$(function() {
var Profile = Backbone.Model.extend();
var ProfileList = Backbone.Collection.extend({
model: Profile,
url: 'data.php'
});
var ProfileView = Backbone.View.extend({
el: "#profiles",
template: _.template($('#profileTemplate').html()),
render: function(eventName) {
_.each(this.model.models, function(profile){
var profileTemplate = this.template(profile.toJSON());
$(this.el).append(profileTemplate);
}, this);
return this;
}
});
var profiles = new ProfileList();
var profilesView = new ProfileView({model: profiles});
profiles.fetch({reset: true});
//profiles.bind('reset', function () { console.log(profiles); });
profiles.bind('reset', function () {
profilesView.render();
});
});
答案 0 :(得分:1)
简单解决方案将是:
profiles.fetch({reset: true});
setInterval(
function() {
profiles.fetch({reset: true});
}, 1000 // Time in milliseconds
);
我不会说这是一个很好的解决方案,但我希望你能得到这个想法。据我所知,在Backbone中没有实现间隔提取或类似的东西 - 所以你几乎必须建立自己的。
修改强>
这可能是一个更好的解决方案,我更喜欢它。
var ProfileList = Backbone.Collection.extend({
model : Profile,
url : "data.php",
xhr : null,
interval: null,
fetchWithInterval: function(options) {
var options = options || {},
self = this;
this.interval = setInterval(function(){
if(self.xhr !== null && self.xhr.readyState !== 4) {
return;
}
self.xhr = self.constructor.__super__.fetch.apply(self, options);
}, 1000);
this.xhr = self.constructor.__super__.fetch.apply(self, options);
},
stopFetchWithInterval: function() {
clearInterval(this.interval);
}
});
与profiles.fetchWithInterval({reset: true});
一起使用,您可以使用profiles.stopFetchWithInterval()
停止播放。
它还管理xhr
,因此如果AJAX调用未完成,则不会启动新的调用。如果您想以较小的间隔进行提取,或者由于某种原因您的API速度很慢,这非常方便。