Skip to content

Commit f1e14a3

Browse files
committed
fixuP
1 parent 8844ee6 commit f1e14a3

1 file changed

Lines changed: 18 additions & 11 deletions

File tree

lib/dispatcher/dispatcher.js

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,12 @@ const kOnConnect = Symbol('onConnect')
4444
const kOnDisconnect = Symbol('onDisconnect')
4545
const kOnConnectionError = Symbol('onConnectionError')
4646

47+
const registry = new FinalizationRegistry(({ dispatcher, handlers }) => {
48+
for (const [event, listener] of handlers) {
49+
dispatcher.off(event, listener)
50+
}
51+
});
52+
4753
class ComposedDispatcher extends Dispatcher {
4854
#dispatcher
4955
#dispatch
@@ -54,17 +60,18 @@ class ComposedDispatcher extends Dispatcher {
5460
this.#dispatcher = dispatcher
5561
this.#dispatch = dispatch
5662

57-
this[kOnDrain] = (...args) => this.emit('drain', ...args)
58-
this[kOnConnect] = (...args) => this.emit('connect', ...args)
59-
this[kOnDisconnect] = (...args) => this.emit('disconnect', ...args)
60-
this[kOnConnectionError] = (...args) => this.emit('connectionError', ...args)
61-
62-
// TODO (fix): These must be weak references...
63-
this.#dispatcher
64-
.on('drain', this[kOnDrain])
65-
.on('connect', this[kOnConnect])
66-
.on('disconnect', this[kOnDisconnect])
67-
.on('connectionError', this[kOnConnectionError])
63+
const weakThis = new WeakRef(this)
64+
const handlers = []
65+
66+
for (const event of ['drain', 'connect', 'disconnect', 'connectionError']) {
67+
const listener = function (...args) {
68+
weakThis.deref()?.emit(event, ...args)
69+
}
70+
handlers.push([event, listener])
71+
dispatcher.on(event, listener)
72+
}
73+
74+
registry.register(this, { dispatcher, handlers })
6875
}
6976

7077
dispatch (...args) {

0 commit comments

Comments
 (0)