skip to content

In a Stimulus controller, what event does this.dispatch("expired", { detail }) send, and how does another controller's data-action receive it?

level: middleimportance: should knowfreq 38%

answer

  1. prefix defaults to the identifier
  2. countdown:expired as the action's event
  3. bubbles and cancelable default true
  4. @window when the receiver isn't an ancestor
  5. payload in event.detail

basics

~10 s

this.dispatch("expired") fires a bubbling, cancelable CustomEvent named countdown:expired on the controller's element and returns it. Another controller routes it with data-action="countdown:expired->question-navigator#finish" on an ancestor, or with @window when it sits elsewhere, and reads event.detail.

solid answer

~30 s

`this.dispatch(name, options)` builds a `CustomEvent` and dispatches it on `this.element` by default. The type is prefixed with the controller's identifier, so `dispatch("expired")` in the countdown controller emits `countdown:expired`. The options are `target`, `detail` (default `{}`), `prefix` (default the identifier; a falsy prefix sends the bare name), `bubbles` and `cancelable`, both true by default. The receiver subscribes declaratively: `data-action="countdown:expired->question-navigator#finish"` on the same element or an ancestor of the countdown, or `countdown:expired@window->question-navigator#finish` when the navigator sits elsewhere. The handler reads the payload from `event.detail`. `dispatch` returns the event, so the countdown can check `event.defaultPrevented` to let a listener veto its default behaviour.

code

javascript · 6 lines
javascript
// countdown_controller.js (excerpt)
secondsValueChanged(seconds) {
  if (seconds > 0) return
  const event = this.dispatch("expired", { detail: { attemptId: this.attemptValue } })
  if (!event.defaultPrevented) this.element.closest("form")?.requestSubmit()
}

go deeper

for a junior

Recall that this.dispatch prefixes the event with the identifier and that another controller listens with data-action.

for a middle

Explain the dispatch options and defaults, when a receiver needs @window, and how detail and defaultPrevented work.

for a senior

Design event names and payloads that keep dispatchers ignorant of their listeners, and diagnose silent misses from wrong names or missing global targets.

for a principal

Use dispatched events as the page's internal message vocabulary, kept small and documented, so new behaviour subscribes without editing emitters.

## What dispatch does `dispatch` is a convenience method on every Stimulus controller. It creates a `CustomEvent`, dispatches it, and returns it: ```javascript const event = this.dispatch("expired", { detail: { attemptId: 42 } }) ``` In the exam-practice app the countdown controller calls this when the clock reaches zero. The countdown does not know who cares: the question navigator might lock answers, an autosave controller might flush the last answer, and a banner controller might show a message. ## The options and their defaults | option | default | effect | |---|---|---| | `target` | `this.element` | where the event is dispatched; can be another element, `window` or `document` | | `detail` | `{}` | the payload, read as `event.detail` | | `prefix` | the controller's identifier | prepended with a colon; a falsy prefix sends the bare name | | `bubbles` | `true` | the event travels up through ancestors | | `cancelable` | `true` | listeners may call `preventDefault()` | So `this.dispatch("expired")` inside the controller registered as `countdown` emits an event whose type is `countdown:expired`. Inside a namespaced controller such as `exams--countdown`, the type is `exams--countdown:expired`. ## Receiving it with data-action Because the event is a DOM event, the receiving controller subscribes with an ordinary action descriptor whose event name is the full prefixed type: - **Same element or an ancestor.** `data-action="countdown:expired->question-navigator#finish"` on the navigator's element works when the countdown's element is inside it (or is the same element), because the event bubbles through it. - **Anywhere else.** When the navigator is a sibling in another part of the layout, the event never passes through its element. Append `@window` (or `@document`): `countdown:expired@window->question-navigator#finish`. The global listener belongs to the navigator controller and is removed with it. The handler receives the event like any action method: ```javascript finish({ detail: { attemptId } }) { this.lockAnswers() } ``` `event.params` is still present, but it holds action parameters from the navigator's own element, not the payload; the payload is `event.detail`. ## Letting listeners veto Because `cancelable` defaults to true and `dispatch` returns the event, the dispatcher can ask permission: 1. The countdown dispatches `expired` before auto-submitting. 2. A practice-mode controller listening for it calls `event.preventDefault()` to keep the attempt open. 3. Back in the countdown, `if (event.defaultPrevented) return` skips the auto-submit. Listeners attached through `data-action` have already run by the time `dispatch` returns, so the check is reliable. ## Choosing names and payloads - Name events for what happened (`expired`, `paused`), not for what the listener should do (`lockNavigator`); the dispatcher should not know its audience. - Keep `detail` small and serialisable: ids and flags rather than controller instances or DOM nodes, so any listener can use it. - Use `prefix: false` only for an event that deliberately pretends to come from elsewhere, for example to match an existing listener; the identifier prefix keeps event names collision-free. ## A worked flow 1. `tick()` lowers `secondsValue` to 0. 2. `secondsValueChanged(0, 1)` calls `this.dispatch("expired", { detail: { attemptId } })`. 3. The `countdown:expired` event bubbles to `window`, where the navigator's `@window` descriptor routes it to `finish()`, which locks the answer buttons. 4. An autosave controller on an ancestor of the countdown hears the same event through a plain descriptor and saves the current answer. 5. Neither listener called `preventDefault()`, so the countdown submits the attempt form. Adding a third reaction, such as a banner, means adding one `data-action` attribute; the countdown never changes. ## Pitfalls - **Wrong event name in the descriptor.** `expired->question-navigator#finish` waits for an event literally named `expired`, which the countdown never sends. - **Missing `@window`.** A sibling's descriptor without a global target never fires, with no error. - **Listener not yet connected.** An event fired before the receiving controller connects is simply lost; Stimulus does not replay it.

  • When does a receiver need @window rather than a plain descriptor?
    Whenever its element is neither the dispatching element nor one of its ancestors. A bubbling event only passes through the dispatcher's ancestors, so a sibling never sees it on its own element; `@window` or `@document` installs the listener where every bubbling event ends up.
  • How would you dispatch an unprefixed event or target another element?
    Pass `prefix: false` to send the bare name, and `target:` to dispatch on another element, `window` or `document`. Both are options of `this.dispatch`, alongside `detail`, `bubbles` and `cancelable`.

  • this.dispatch sends the bare event name with no controller prefix
  • A sibling controller hears a dispatched event without @window or @document
  • The dispatched payload arrives in event.params
  • Events from this.dispatch cannot be cancelled by listeners
  • this.dispatch defaults to bubbles: false