From 88554819f3c807c9f31236ed99491b2ae27c8347 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Tue, 25 Jun 2024 20:40:55 +0200 Subject: [PATCH] fixuP --- lib/dispatcher/dispatcher.js | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/lib/dispatcher/dispatcher.js b/lib/dispatcher/dispatcher.js index 4f23e6e3485..c57415cc9e1 100644 --- a/lib/dispatcher/dispatcher.js +++ b/lib/dispatcher/dispatcher.js @@ -39,10 +39,11 @@ class Dispatcher extends EventEmitter { } } -const kOnDrain = Symbol('onDrain') -const kOnConnect = Symbol('onConnect') -const kOnDisconnect = Symbol('onDisconnect') -const kOnConnectionError = Symbol('onConnectionError') +const registry = new FinalizationRegistry(({ dispatcher, handlers }) => { + for (const [event, listener] of handlers) { + dispatcher.off(event, listener) + } +}); class ComposedDispatcher extends Dispatcher { #dispatcher @@ -54,17 +55,18 @@ class ComposedDispatcher extends Dispatcher { this.#dispatcher = dispatcher this.#dispatch = dispatch - this[kOnDrain] = (...args) => this.emit('drain', ...args) - this[kOnConnect] = (...args) => this.emit('connect', ...args) - this[kOnDisconnect] = (...args) => this.emit('disconnect', ...args) - this[kOnConnectionError] = (...args) => this.emit('connectionError', ...args) - - // TODO (fix): These must be weak references... - this.#dispatcher - .on('drain', this[kOnDrain]) - .on('connect', this[kOnConnect]) - .on('disconnect', this[kOnDisconnect]) - .on('connectionError', this[kOnConnectionError]) + const weakThis = new WeakRef(this) + const handlers = [] + + for (const event of ['drain', 'connect', 'disconnect', 'connectionError']) { + const listener = function (...args) { + weakThis.deref()?.emit(event, ...args) + } + handlers.push([event, listener]) + dispatcher.on(event, listener) + } + + registry.register(this, { dispatcher, handlers }) } dispatch (...args) {