Created
August 12, 2014 20:27
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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