From 07502575ebb4b01a64f9fd3601decd390cdb8d58 Mon Sep 17 00:00:00 2001 From: Calvin Montgomery Date: Sat, 23 Jun 2018 16:39:57 -0700 Subject: [PATCH] Add once() to clientside ws shim --- www/js/ws.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/www/js/ws.js b/www/js/ws.js index 52d40528..e51a3437 100644 --- a/www/js/ws.js +++ b/www/js/ws.js @@ -27,6 +27,11 @@ this.listeners(frame).push(callback); }; + WSShim.prototype.once = function on(frame, callback) { + callback._once = true; + this.listeners(frame).push(callback); + }; + WSShim.prototype.emit = function emit(frame, payload, ack) { var message = { type: TYPE_FRAME, @@ -43,13 +48,25 @@ }; WSShim.prototype._emit = function _emit(frame, payload) { + var hasOnce = false; + this.listeners(frame).forEach(function (cb) { try { + if (cb._once) { + hasOnce = true; + } + cb(payload); } catch (error) { console.error('Error in callback for ' + frame + ': ' + error); } }); + + if (hasOnce) { + this._listeners[frame] = this._listeners[frame].filter(function (cb) { + return !cb._once; + }); + } }; WSShim.prototype._onopen = function _onopen() {