Skip to content

Commit a5b58c7

Browse files
committed
Allow socket to be reactivated cleanly if it was previously destroyed
1 parent 279efb2 commit a5b58c7

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

lib/scsocket.js

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -138,18 +138,16 @@ var SCSocket = function (opts) {
138138
this.options.query = querystring.parse(this.options.query);
139139
}
140140

141-
if (this.options.autoConnect) {
142-
this.connect();
143-
}
144-
145141
this._channelEmitter = new Emitter();
146142

147-
if (isBrowser && this.disconnectOnUnload && global.addEventListener) {
148-
this._unloadHandler = function () {
149-
self.disconnect();
150-
};
143+
this._unloadHandler = function () {
144+
self.disconnect();
145+
};
151146

152-
global.addEventListener('beforeunload', this._unloadHandler, false);
147+
if (this.options.autoConnect) {
148+
this.connect();
149+
} else {
150+
this.activate();
153151
}
154152
};
155153

@@ -256,6 +254,8 @@ SCSocket.prototype.deauthenticate = function (callback) {
256254
SCSocket.prototype.connect = SCSocket.prototype.open = function () {
257255
var self = this;
258256

257+
this.activate();
258+
259259
if (this.state == this.CLOSED) {
260260
this.pendingReconnect = false;
261261
this.pendingReconnectTimeout = null;
@@ -316,10 +316,19 @@ SCSocket.prototype.disconnect = function (code, data) {
316316
}
317317
};
318318

319+
SCSocket.prototype.activate = function () {
320+
if (isBrowser && this.disconnectOnUnload && global.addEventListener && !this.active) {
321+
global.addEventListener('beforeunload', this._unloadHandler, false);
322+
}
323+
this._clientMap[this.clientId] = this;
324+
this.active = true;
325+
};
326+
319327
SCSocket.prototype.destroy = function (code, data) {
320-
if (this._unloadHandler) {
328+
if (isBrowser && global.removeEventListener) {
321329
global.removeEventListener('beforeunload', this._unloadHandler, false);
322330
}
331+
this.active = false;
323332
this.disconnect(code, data);
324333
delete this._clientMap[this.clientId];
325334
};

0 commit comments

Comments
 (0)