Skip to content

Instantly share code, notes, and snippets.

@logicalparadox
Created April 29, 2012 17:07
Show Gist options
  • Select an option

  • Save logicalparadox/2551971 to your computer and use it in GitHub Desktop.

Select an option

Save logicalparadox/2551971 to your computer and use it in GitHub Desktop.
Stack Socket.io event callbacks.
module.exports = function (socketio) {
socketio.Socket.prototype.stack = function () {
var ev = arguments[0]
, cbs = Array.prototype.slice.call(arguments, 1);
this.on(ev, function () {
var args = Array.prototype.slice.call(arguments, 0)
, cbl = cbs.slice()
, fn = ('function' === typeof args[args.length - 1])
? args[args.length - 1]
: null
, data = (!(args.length === 1 && fn))
? args[0]
: null;
var context = {
event: ev
, socket: this
, session: this.handshake.session
};
var next = function (err) {
if (err && fn) {
fn(err.toString());
} else if (!err) {
var cb = cbl.shift();
if (cbList.length) return cb(context, data, next);
if (cb) return cb(context, data, fn);
}
};
next();
});
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment