liveBook · Manning

Emit

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

A book-specific component function that dispatches an event or command to the application's dispatcher.

emit is a small component function that forwards an event or command, with an optional payload, to the application’s dispatcher. It keeps user-input handlers shorter than calling dispatcher.dispatch() directly. section 5.2.4 section 11.2.4

Use emit to:

  • Dispatch named commands such as update-current-todo or add-todo from event handlers. section 6.3.3
  • Pass payloads when a handler needs data, such as edited text, an input value, or an item index. section 6.3.3
  • Let components ignore the function when they do not dispatch commands. section 5.2.4
  • Carry events upward from child components while props carry data downward from parents. section 11.0

Dispatching from a component

function CreateTodo({ currentTodo }, emit) { return h('input', { value: currentTodo, on: { input: ({ target }) => emit('update-current-todo', target.value) } }) } section 6.3.3

Listing 11.15 Emitting events from the component (component.js)
export function defineComponent({ render, state, ...methods }) {
  class Component {
 // --snip-- //
    emit(eventName, payload) {
      this.#dispatcher.dispatch(eventName, payload)
    }
  }

 // --snip-- //

  return Component
}

The component method delegates directly to its private dispatcher, preserving a concise public API for event handlers. section 11.2.4

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

How deep it goes
Defines emit as a dispatcher wrapper and demonstrates handlers with payloads, without detailing dispatcher internals.
Examples
Uses todo creation, input updates, editing, saving, cancellation, and removal as concrete dispatch examples.
What it assumes
Uses component functions, state, event handlers, and a dispatcher while teaching the shorter emit API.
What you can do after
Apply it via component event handlers to dispatch named events with optional payloads.
How it connects
Links components with dispatchers, events, props, state, reducers, and the DOM.

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.