From 9b1ba7e592bc62ed0ec7f0b9a4c7d8b50d343411 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Mon, 10 Dec 2012 14:40:07 +0100 Subject: [PATCH] Disconnect socket once all namespaces are disconnected In order to support this, only user requested namespaces are registered. This will also fix an issue where explicitly disconnected namespaces don't stop receiving events through Socket#publish(). --- lib/namespace.js | 3 +-- lib/socket.js | 26 ++++++++++++++++++++++++-- 2 files changed, 25 insertions(+), 4 deletions(-) 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); + } }; /**