From f1e14a34ed25e2878402bf1b3644e152e5cb9a88 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 | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/lib/dispatcher/dispatcher.js b/lib/dispatcher/dispatcher.js index 4f23e6e3485..3577ce9dae5 100644 --- a/lib/dispatcher/dispatcher.js +++ b/lib/dispatcher/dispatcher.js @@ -44,6 +44,12 @@ 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 #dispatch @@ -54,17 +60,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) {