liveBook · Manning

Subscribe

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

A dispatcher method that registers a handler for a specified event or command and returns a function for removing that registration.

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

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

How deep it goes
Explains Map storage, duplicate checks, array insertion, and returned cleanup closures, while deferring dispatch implementation.
Examples
Uses a removeTodoHandler example that accepts a to-do index and calls a reducer to update state.
What it assumes
Assumes basic JavaScript functions and arrays while introducing command dispatch, subscriptions, and ES2020 private fields.
What you can do after
Build it from scratch by storing handlers, rejecting duplicates, and returning a function that unregisters each handler.
How it connects
Connects command handlers with dispatchers, command payloads, reducers, and state management.

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.