1
0
mirror of https://github.com/node-red/node-red.git synced 2023-10-10 13:36:53 +02:00

Updated to cover the removal of individual event handlers

This commit is contained in:
Phil Day 2022-05-09 15:39:12 +01:00 committed by Steve-Mcl
parent 1eea371124
commit 03484fd5cd

View File

@ -693,7 +693,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) {
@ -764,7 +764,7 @@ module.exports = function(RED) {
node.connecting = false;
node.connected = false;
}
if(node.client) { node._clientRemoveAllListeners(); }
if(node.client) { node._clientRemoveListeners(); }
node.connecting = false;
node.connected = false;
callback && typeof callback == "function" && callback();
@ -846,7 +846,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];
}
@ -914,7 +914,7 @@ module.exports = function(RED) {
node.on('close', function(done) {
node.disconnect(function() {
if(node.client) {
node._clientRemoveAllListeners();
node._clientRemoveListeners();
}
done();
});
@ -923,19 +923,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
/**
* 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)) {
if (event && event !== l.e) { return true; }
if (handler && handler !== l.h) { return true; }
node.client.removeListener(l.event, l.f)
return false;
}
else
return true;
return false; //found and removed, fliter out this one
})
}