Skip to content

Instantly share code, notes, and snippets.

@mcsf
Created August 12, 2014 20:27
Show Gist options
  • Save mcsf/63a5b8195f5ad255f684 to your computer and use it in GitHub Desktop.
Save mcsf/63a5b8195f5ad255f684 to your computer and use it in GitHub Desktop.
Autofetch in a Backbone Model/Collection with throttling; autopause if page not in view
Collection = Backbone.Collection.extend({
// ...
autofetch: function(interval, throttle) {
var maybeFetch = function() {
if (! document.hidden) { this.fetch(); }
}.bind(this);
this.fetch = _.throttle(this.fetch, throttle * 1000);
this.fetchId = setInterval(maybeFetch, interval * 1000);
$(document).on('visibilitychange', maybeFetch);
}
});
CollectionGetInstance = (function() {
var instance;
return function() {
if (! instance) {
instance = new Collection();
instance.promise = instance.fetch();
instance.autofetch(5, 5);
}
return instance;
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment