From 7f3bd32d8842dfe54088180fd439098560feddde Mon Sep 17 00:00:00 2001 From: Charlie Powell <31997505+cp2004@users.noreply.github.com> Date: Mon, 16 Jan 2023 16:15:20 +0000 Subject: [PATCH] :sparkles: Add `removeMessage` to OctoPrint socket (#4708) --- docs/jsclientlib/socket.rst | 17 +++++++++++++++++ src/octoprint/static/js/app/client/socket.js | 12 ++++++++++++ 2 files changed, 29 insertions(+) diff --git a/docs/jsclientlib/socket.rst b/docs/jsclientlib/socket.rst index fc4223546..aaf5a5e6a 100644 --- a/docs/jsclientlib/socket.rst +++ b/docs/jsclientlib/socket.rst @@ -60,6 +60,23 @@ :param string message: The type of message for which to register :param function handler: The handler function +.. js:function:: OctoPrintClient.socker.removeMessage(message, handler) + + Removes the ``handler`` for messages of type ``message``. + + .. code-block:: javascript + + const handler = (message) => { + // do something with the message object + }; + + OctoPrint.socket.onMessage("*", handler); + // Use the same reference to the handler function to remove it again + OctoPrint.socket.removeMessage("*", handler); + + :param string message: The type of message for which to remove the handler + :param function handler: The handler function + .. js:function:: OctoPrintClient.socket.sendMessage(type, payload) Sends a message of type ``type`` with the provided ``payload`` to the server. diff --git a/src/octoprint/static/js/app/client/socket.js b/src/octoprint/static/js/app/client/socket.js index 8408e5606..cfa73311f 100644 --- a/src/octoprint/static/js/app/client/socket.js +++ b/src/octoprint/static/js/app/client/socket.js @@ -220,6 +220,18 @@ return this; }; + OctoPrintSocketClient.prototype.removeMessage = function (message, handler) { + if (!this.registeredHandlers.hasOwnProperty(message)) { + // No handlers registered, do nothing + return; + } + + const index = OctoPrint.socket.registeredHandlers[message].indexOf(handler); + if (index > -1) { + OctoPrint.socket.registeredHandlers[message].splice(index, 1); + } + }; + OctoPrintSocketClient.prototype.onReconnectAttempt = function (trial) {}; OctoPrintSocketClient.prototype.onReconnectFailed = function () {}; OctoPrintSocketClient.prototype.onConnected = function () {};