ioBind
Bind and handle trigger of socket.io event for collections.
Guidelines
Do NOT bind to reserved backbone events, such as change
, remove
, and add
.
Proxy these events using different event tags such as update
, delete
, and create
.
The socket.io socket must either exist at window.socket
, Backbone.socket
,
or this.socket
or it must be passed as the second argument.
Example
- Model definition has url:
my_model
- Model instance has id:
abc123
Create a new bind (client-side):
model.ioBind('update', window.io, this.updateView, this);
Send socket.io message (server-side)
socket.emit( 'my_model/abc123:update', { title: 'My New Title' } );
Backbone.Collection.prototype.ioBind = function (eventName, io, callback, context) {
var ioEvents = this._ioEvents || (this._ioEvents = {})
, globalName = this.url + ':' + eventName
, self = this;
if ('function' == typeof io) {
context = callback;
callback = io;
io = this.socket || window.socket || Backbone.socket;
}
var event = {
name: eventName,
global: globalName,
cbLocal: callback,
cbGlobal: function (data) {
self.trigger(eventName, data);
}
};
this.bind(event.name, event.cbLocal, context);
io.on(event.global, event.cbGlobal);
if (!ioEvents[event.name]) {
ioEvents[event.name] = [event];
} else {
ioEvents[event.name].push(event);
}
return this;
};