Created
March 25, 2012 12:04
-
-
Save julesbou/2193177 to your computer and use it in GitHub Desktop.
Integrate SocketIO events into your Backbone.Collection
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
// 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)) | |
} | |
} | |
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
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