diff --git a/packages/node_modules/@node-red/nodes/core/network/10-mqtt.js b/packages/node_modules/@node-red/nodes/core/network/10-mqtt.js index 666e01f62..2f600796f 100644 --- a/packages/node_modules/@node-red/nodes/core/network/10-mqtt.js +++ b/packages/node_modules/@node-red/nodes/core/network/10-mqtt.js @@ -755,7 +755,7 @@ module.exports = function(RED) { } setStatusConnected(node, true); // Remove any existing listeners before resubscribing to avoid duplicates in the event of a re-connection - node._clientRemoveAllListeners('message'); + node._clientRemoveListeners('message'); // Re-subscribe to stored topics for (var s in node.subscriptions) { @@ -823,7 +823,7 @@ module.exports = function(RED) { if(node.connected || node.connecting) { setStatusDisconnected(node, true); } - if(node.client) { node._clientRemoveAllListeners(); } + if(node.client) { node._clientRemoveListeners(); } node.connecting = false; node.connected = false; callback && typeof callback == "function" && callback(); @@ -906,7 +906,7 @@ module.exports = function(RED) { if (sub) { if (sub[ref]) { if(node.client) { - node.client.removeListener('message',sub[ref].handler); + node._clientRemoveListeners('message',sub[ref].handler); } delete sub[ref]; } @@ -997,7 +997,7 @@ module.exports = function(RED) { node.on('close', function(done) { node.disconnect(function() { if(node.client) { - node._clientRemoveAllListeners(); + node._clientRemoveListeners(); } done(); }); @@ -1006,19 +1006,33 @@ module.exports = function(RED) { // Helper functions to track the event listners we add to the // client. The mqtt client also uses it own set of listeners // so we can't use removeAllListeners() wothout breaking it - node._clientOn = function(event, f) { + + /** + * Add an event handlers to the MQTT.js client + * @param {string} [event] The name of the event (optional) + * @param {function} [handler] The handler for this event + */ + node._clientOn = function(event, f) { node.clientListeners.push({event, f}) node.client.on(event, f) } - node._clientRemoveAllListeners = function(event) { + /** + * Remove event handlers from the MQTT.js client & only the events + * that we attached in {@link node._clientOn `node._clientOn`}. + * * If `event` is omitted, then all events matching `handler` are removed + * * If `handler` is omitted, then all events named `event` are removed + * * If both parameters are omitted, then all events are removed + * @param {string} [event] The name of the event (optional) + * @param {function} [handler] The handler for this event + */ + node._clientRemoveListeners = function(event, handler) { node.clientListeners = node.clientListeners.filter((l) => { - if (!event || (event == l.e)) { - node.client.removeListener(l.event, l.f) - return false; - } - else - return true; + if (event && event !== l.e) { return true; } + if (handler && handler !== l.h) { return true; } + node.client.removeListener(l.event, l.f) + return false; //found and removed, fliter out this one + }) }