Reputation: 5444
I ve created a backbone model, which fetch json from a server. However, i want to update view with the new data, in specific time interval, not every time that the server sends data. What should i use with purpose to update backbone view every n milliseconds? I ve got the above code.
$(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();
});
});
Upvotes: 0
Views: 144
Reputation: 2015
A simple solution would be:
profiles.fetch({reset: true});
setInterval(
function() {
profiles.fetch({reset: true});
}, 1000 // Time in milliseconds
);
I wouldn't say that it's a beautiful solution but I hope you get the idea. As far as I know there is no interval fetch, or something similar, implemented in Backbone - so you pretty much have to build your own.
EDIT
This is probably a better solution, I like it more atleast.
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);
}
});
Use it with profiles.fetchWithInterval({reset: true});
and you can stop it with profiles.stopFetchWithInterval()
.
It also manages the xhr
, so if the AJAX call isn't finished it will not start a new one. This is pretty handy if you want to fetch with a small interval or when your API is slow for some reason.
Upvotes: 1