subscribe() registers a handler for a named command and returns an unsubscribe function. This lets views stop receiving commands when they are removed from the DOM. section 5.1.3
The implementation performs four small tasks:
- Create an empty handler array when the command name is new. section 5.1.3
- Ignore duplicate registrations of the same handler. section 5.1.3
- Store the handler so dispatch() can call it with the command payload. section 5.1.3
- Return a closure that removes the handler from its array. section 5.1.3
Listing 5.1 Registering handlers to respond to commands (dispatcher.js)
export class Dispatcher {
#subs = new Map()
subscribe(commandName, handler) {
if (!this.#subs.has(commandName)) { #1
this.#subs.set(commandName, [])
}
const handlers = this.#subs.get(commandName)
if (handlers.includes(handler)) { #2
return () => {}
}
handlers.push(handler) #3
return () => { #4
const idx = handlers.indexOf(handler)
handlers.splice(idx, 1)
}
}
}
The complete Dispatcher implementation shows Map-based storage, duplicate protection, handler registration, and closure-based removal. section 5.1.3
