Dispatch sends an application command to the handlers registered for its name, passing along a payload. After handling, it runs every after-command handler. section 5.1.3
A dispatcher operation performs three focused responsibilities:
- Looks up handlers associated with the command name and invokes each one with the payload. section 5.1.3
- Warns when no handlers are registered for the command. section 5.1.3
- Runs registered after-command handlers after the command handlers finish, commonly allowing the application to render updated state. section 5.1.3 section 5.2.4
Removing a to-do item
A component can dispatch `remove-todo` with the item index as its payload. The matching handler updates application state, and an after-command handler can render the resulting view. Components may call `emit('remove-todo', todoIdx)` as a shorter interface. section 5.2.4
Listing 5.3 Dispatching a command given its name and payload (dispatcher.js)
export class Dispatcher {
// --snip-- //
dispatch(commandName, payload) {
if (this.#subs.has(commandName)) { #1
this.#subs.get(commandName).forEach((handler) => handler(payload))
} else {
console.warn(`No handlers for command: ${commandName}`)
}
this.#afterHandlers.forEach((handler) => handler()) #2
}
}
Inspect the compact JavaScript implementation of dispatching by command name and payload, including missing-handler warnings and after-command execution. section 5.1.3
