diff --git a/lib/namespace.js b/lib/namespace.js index 3c538a77c..894149c59 100644 --- a/lib/namespace.js +++ b/lib/namespace.js @@ -123,8 +123,7 @@ if (this.name === '') { this.socket.disconnect(); } else { - this.packet({ type: 'disconnect' }); - this.$emit('disconnect'); + this.socket.disconnectNamespace(this.name); } return this; diff --git a/lib/socket.js b/lib/socket.js index 1dd11e2ec..677c43801 100644 --- a/lib/socket.js +++ b/lib/socket.js @@ -86,6 +86,26 @@ return this.namespaces[name]; }; + /** + * Disconnects a namespace, and the socket connection if all namespaces have + * been disconnected. + * + * @api private + */ + + Socket.prototype.disconnectNamespace = function (name) { + if (this.namespaces[name]) { + var nsp = this.of(name); + nsp.packet({ type: 'disconnect' }); + nsp.$emit('disconnect'); + delete this.namespaces[name]; + + if (Object.keys(this.namespaces).length === 0) { + this.disconnect(); + } + } + }; + /** * Emits the given event to the Socket and all namespaces * @@ -339,7 +359,7 @@ Socket.prototype.disconnect = function () { if (this.connected || this.connecting) { if (this.open) { - this.of('').packet({ type: 'disconnect' }); + this.packet({ type: 'disconnect' }); } // handle disconnection immediately @@ -440,7 +460,9 @@ */ Socket.prototype.onPacket = function (packet) { - this.of(packet.endpoint).onPacket(packet); + if (this.namespaces[packet.endpoint]) { + this.of(packet.endpoint).onPacket(packet); + } }; /**