Comment by arnorhs
Comment by arnorhs 3 days ago
I'm not a huge fan of using CustomEvent for this.. esp. in terms of interoperability (which for these <kb challenges probably doesnt matter)
personally, i'll just roll with something like this which also is typed etc:
export function createPubSub<T extends readonly any[]>() {
const l = new Set<(...args: T) => void>()
return {
pub: (...args: T) => l.forEach((f) => f(...args)),
sub: (f: (...args: T) => void) => l.add(f) && (() => l.delete(f)),
}
}
// usage:
const greetings = createPubSub<[string]>()
const unsubscribe = greetings.sub((name) => {
console.log('hi there', name)
})
greetings.pub('Dudeman')
unsubscribe()
If listeners of this implementation aren’t unsubscribed they can’t be garbage collected, and in a real world codebase that means memory leaks are inevitable. EventDispatcher has weak refs to its listeners, so it doesn’t have this problem.