liveBook · Manning

Dispatch

As explained in Build a Frontend Web Framework (From Scratch)

A dispatcher operation that sends a command for handling, executing its registered handlers and after-command handlers.

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

How Build a Frontend Web Framework (From Scratch) covers it

How deep it goes
Explains command lookup, payload passing, missing-handler warnings, and after-command execution through a small JavaScript implementation.
Examples
Uses add-todo, remove-todo, start-editing-todo, a counter exercise, and a component dispatching a to-do removal.
What it assumes
Assumes JavaScript event listeners and introduces application-domain commands as requests such as add-todo and remove-todo.
What you can do after
Apply it via a Dispatcher or emit() function to connect component input with registered state updates.
How it connects
Connects browser events, application commands, state management, reducers, components, and rendering.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Frontend Web Framework (From Scratch). The section links point to the parts of the book it draws on.