Skip to content

Instantly share code, notes, and snippets.

@julesbou
Created March 25, 2012 12:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julesbou/2193177 to your computer and use it in GitHub Desktop.
Save julesbou/2193177 to your computer and use it in GitHub Desktop.
Integrate SocketIO events into your Backbone.Collection
// Let you listen to SocketIO events into your Collection
var socket
Backbone.Collection.prototype.initialize = function() {
var events = this.socketEvents
for (var eventName in events) {
var method = events[eventName];
if (!_.isFunction(method)) method = this[events[eventName]];
if (!method) throw new Error('Method "' + events[eventName] + '" does not exist');
socket.on(eventName, _.bind(method, this))
}
}
var MyCollection = Backbone.Collection.extend({
socketEvents: {
'add_item': 'add'
}
})
var coll = new MyCollection()
// emit `add_item` event in your server side script
// ..
// automatically, you item has been added to the collection
coll.size()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment