Skip to content

Commit

Permalink
fixuP
Browse files Browse the repository at this point in the history
  • Loading branch information
ronag committed Jun 25, 2024
1 parent 8844ee6 commit 67de892
Showing 1 changed file with 17 additions and 15 deletions.
32 changes: 17 additions & 15 deletions lib/dispatcher/dispatcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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) {
Expand Down

0 comments on commit 67de892

Please sign in to comment.