Backbone.ioBind

ioBind is a plugin for Backbone that makes it easy to bind Socket.io events to models and collections. This can be as easy as using the included replacement for Backbone.sync, or you can bind to your own events. Or both!

Latest Update to Github

Loading...
Loading...
Fork me on GitHub
git clone https://github.com/logicalparadox/backbone.iobind.git

Backbone.sync

Backbone.sync()

Replaces default Backbone.sync function with socket.io transport

Assumptions

Currently expects active socket to be located at window.socket,
Backbone.socket or the sync'ed model own socket.
See inline comments if you want to change it.

Server Side

socket.on('todos:create', function (data, fn) {
 ...
 fn(null, todo);
});
socket.on('todos:read', ... );
socket.on('todos:update', ... );
socket.on('todos:delete', ... );
View Source
Backbone.sync = function (method, model, options) {
  var getUrl = function (object) {
    if (!(object && object.url)) return null;
    return _.isFunction(object.url) ? object.url() : object.url;
  };

  var cmd = getUrl(model).split('/')
    , namespace = (cmd[0] !== '') ? cmd[0] : cmd[1]; // if leading slash, ignore

  var params = _.extend({
    req: namespace + ':' + method
  }, options);

  params.data = model.toJSON() || {};

  // If your socket.io connection exists on a different var, change here:
  var io = model.socket || window.socket || Backbone.socket;

  io.emit(namespace + ':' + method, params.data, function (err, data) {
    if (err) {
      options.error(err);
    } else {
      options.success(data);
    }
  });
};