diff --git a/lib/namespace.js b/lib/namespace.js index eec845f3a5..8992909628 100644 --- a/lib/namespace.js +++ b/lib/namespace.js @@ -134,11 +134,23 @@ Namespace.prototype.add = function(client, fn){ var socket = new Socket(this, client); var self = this; this.run(socket, function(err){ - if (err) return socket.err(err.data || err.message); - self.sockets.push(socket); - self.emit('connect', socket); - self.emit('connection', socket); - socket.onconnect(); + process.nextTick(function(){ + if (err) return socket.err(err.data || err.message); + + // track socket + self.sockets.push(socket); + + // it's paramount that the internal `onconnect` logic + // fires before user-set events to prevent state order + // violations (such as a disconnection before the connection + // logic is complete) + socket.onconnect(); + if (fn) fn(); + + // fire user-set events + self.emit('connect', socket); + self.emit('connection', socket); + }); }); return socket; };