Skip to content

Instantly share code, notes, and snippets.

@milosdakic
Created August 13, 2012 03:27
Show Gist options
  • Save milosdakic/3336736 to your computer and use it in GitHub Desktop.
Save milosdakic/3336736 to your computer and use it in GitHub Desktop.
Backbone.js Collection/Model Stream mixin
/**
* Stream collection/model data.
* @exports mixins/Stream
* @module Stream
*/
var Stream = {
/**
* Is the collection steaming?
*
* @property streaming
* @type bool
*/
streaming: false,
/**
* Set interval timeout for streaming.
*
* @property interval Default to 15 seconds
* @type int
*/
interval: 15000,
/**
* Start streaming the collections data.
*
* @method stream
* @param object options Options that are passed to fetch.
* @return object
*/
stream: function(options) {
options || (options = {});
// Unstream exisiting fetch
if (this.isStreaming()) {
this.unstream();
}
// Timeout method, bind to self
var update = _.bind(function() {
// Get interval from options or object
var interval = options.interval ? options.interval : this.interval;
// Make sure we have an interval before we set timeouts
if (_.isNumber(interval)) {
this.streaming = true;
this._fetcher = setTimeout(update, interval);
}
// Also pass on these options to the Backbone fetch method
this.fetch(options);
}, this);
// Initial call to setup timeout and fetch collection
update();
return this;
},
/**
* Clear the streaming
*
* @return void
*/
unstream: function() {
// Clear timeout before removing property
clearTimeout(this._fetcher);
// Remove property from the object
delete this._fetcher;
// reset flag
this.streaming = false;
// return self
return this;
},
/**
* Set interval time in ms (milliseconds)
*
* @param int ms Time at which the new interval should be set to.
* @return mixed
*/
setInterval: function(ms) {
if (!ms) return false;
this.interval = ms || (this.inveral);
return this;
},
/**
* Get interval time in ms (milliseconds)
*
* @return int
*/
getInterval: function() {
return this.interval;
},
/**
* Check if the collection is already streaming. Will be useful in some cases.
*
* @return bool
*/
isStreaming: function() {
return this.streaming;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment