I read this implementation of an event emitter on LeetCode and wanted to ask a few questions.
- What purpose does it serve to have the
releasemethod in the return of thesubscribemethod? Why can't I make it its own method? - How do I use the
unsubscribemethod like this and how would I use it if it was its own method? - The author said the reason behind putting the callback inside an object was to be able to add multiple callbacks of the same name. Is that considered good practice?
- Any recommendations as to how to make this implementation better (readability, structure)?
- Why isn't
subscriptionsvariable defined in aconstructor?
Thank you.
class EventEmitter {
subscriptions = new Map()
subscribe(eventName, callback) {
if (!this.subscriptions.has(eventName)) {
this.subscriptions.set(eventName, new Set())
}
const newSub = { callback }
this.subscriptions.get(eventName).add(newSub)
return {
unsubscribe: () => {
const evSub = this.subscriptions.get(eventName)
evSub.delete(newSub)
if (evSub.size === 0)
this.subscriptions.delete(eventName)
}
}
}
emit(eventName, ...args) {
const callbacks = this.subscriptions.get(eventName)
if (!callbacks) return
for (let c of callbacks) {
c.callback(...args)
}
}
}