On an exam-practice page, should a Stimulus question navigator reach the countdown timer through an outlet or through a dispatched event, and what does each choice cost?
answer
- command a known collaborator vs announce
- outlet: host knows the other's API
- event: emitter knows no listeners
- missing outlet throws; unheard event vanishes
- outlets re-query; events aren't replayed
basics
~20 sUse an outlet when the navigator commands or queries a specific countdown, such as pausing it; use a dispatched event when the countdown announces expiry to whoever listens. Outlets couple to its API and throw when absent; unheard events vanish silently.
solid answer
~40 sThe deciding question is the direction of knowledge. When the navigator needs to tell a particular timer to do something or ask it for state, an outlet (`static outlets = ["countdown"]` plus a selector) gives it the controller instance, so `this.countdownOutlet.pause()` is explicit and easy to follow, at the cost of depending on the countdown's method names and handling its absence. When the countdown reports that something happened, `this.dispatch("expired")` lets any number of controllers subscribe through `data-action`, and the countdown stays ignorant of them; the costs are indirection, and the event being lost when no listener is connected, or when a sibling forgot `@window`. On this page I would use both: an outlet for navigator-to-timer commands, an event for timer-to-everyone announcements, and never outlets in both directions.
code
javascript · 11 lines// question_navigator_controller.js: command through an outlet
static outlets = ["countdown"]
review() {
if (this.hasCountdownOutlet) this.countdownOutlet.pause()
}
// countdown_controller.js: announce through an event
secondsValueChanged(seconds) {
if (seconds === 0) this.dispatch("expired", { detail: { attemptId: this.attemptValue } })
}go deeper
Recall that outlets give one controller another's instance, while dispatched events let any controller react through data-action.
Explain how each mechanism is wired and how each fails: a throwing singular outlet getter versus an event nobody heard.
Choose outlets for commands to a known collaborator and events for announcements, and design for absent partners and late Turbo arrivals.
Keep cross-controller dependencies one-directional and documented, and push shared data into server HTML or values rather than a web of controllers.
## Two ways for controllers to talk Stimulus gives controllers two first-class ways to coordinate: - **Outlets**: the host declares `static outlets = ["countdown"]`, its element carries `data-question-navigator-countdown-outlet="#exam-countdown"`, and `this.countdownOutlet` returns the countdown **controller instance**, whose methods and values the host can use directly. - **Dispatched events**: the countdown calls `this.dispatch("expired", { detail })`, a `countdown:expired` event bubbles from its element, and any controller subscribes with `data-action="countdown:expired@window->question-navigator#finish"`. A third route, `this.application.getControllerForElementAndIdentifier(element, "countdown")`, still exists; the Stimulus reference presents it as a last resort, and outlets now cover the same need declaratively. ## Comparing them | concern | outlet | dispatched event | |---|---|---| | who knows whom | host knows the outlet's identifier and methods | emitter knows nobody; listeners know the event name | | direction | host to outlet: commands and queries | emitter to any listeners: announcements | | cardinality | one or many, chosen by the selector | any number of listeners, chosen in markup | | missing partner | singular getter throws; `has...Outlet` guards it | the event is dropped silently | | late arrival | `countdownOutletConnected` fires when the outlet appears | no replay; a listener that connects later never hears it | | answer back | method calls return results directly | little comes back; `defaultPrevented` is the usual signal | | wiring visible in | the host's element (selector) and its class | `data-action` on each listener | ## Applying it to the exam page The page has two flows in opposite directions: 1. **Navigator to timer: "pause while I review flagged questions."** This is a command to one known collaborator, and the navigator needs it to happen. An outlet fits: `if (this.hasCountdownOutlet) this.countdownOutlet.pause()`. The coupling is real but honest, because the navigator genuinely depends on a timer that can pause. 2. **Timer to everyone: "time is up."** The navigator locks answers, an autosave controller flushes the current answer, a banner appears. The countdown should not hold outlets to all of them. A dispatched `countdown:expired` lets each subscribe in markup, and a new subscriber needs no change to the countdown. Making both directions outlets creates a cycle in which each controller depends on the other's API; making both events turns a simple command into an indirect request that nobody is obliged to honour. ## Failure modes to design for - **Outlet absent.** Practice mode without a timer means `this.countdownOutlet` throws. Guard with `hasCountdownOutlet`, or use `countdownOutletConnected` to enable the pause button only when a timer exists. - **Event unheard.** A typo in the event name, or a sibling listener without `@window`, fails with no error. Keep event names in one place in each controller and cover the wiring in a system test. - **Timing across Turbo.** A countdown inside a lazy Turbo Frame connects after the navigator. Outlet callbacks report its arrival; an event fired by the countdown before the navigator connected is gone. - **Replaced elements.** Outlet properties re-query on every read, so after a Turbo swap the host reaches the new countdown. Do not cache `this.countdownOutlet` in a field. ## Testing the wiring - An outlet's contract is a method call, so a system test that clicks "Review flagged" and asserts the clock stopped covers both the selector and the method name. - An event's contract is a name and a payload; the test that matters drives the countdown to zero and asserts every subscriber reacted, because a misspelt event name fails silently and no unit test of either controller alone will catch it. ## A rule of thumb Use an outlet when the sentence is "I need **that** controller to do X", and an event when the sentence is "X just happened". If neither fits because the shared thing is data, such as the current question number that several controllers display, consider putting it in the server-rendered HTML or a value on a common ancestor instead of wiring controllers to each other at all.
- Why not let the countdown hold outlets to every controller that cares about expiry?Then the countdown must know each subscriber's identifier and method, every new subscriber means editing the countdown, and pages without one of them make its singular outlet getters throw. An event lets subscribers opt in from markup while the emitter stays unchanged.
- How do you make an outlet-based command safe on pages without a timer?Guard with `hasCountdownOutlet` before calling, or enable the triggering control only inside `countdownOutletConnected` and disable it in `countdownOutletDisconnected`, so the command can only be issued when a countdown instance exists.
- Where does getControllerForElementAndIdentifier fit today?It returns the controller instance for a given element and identifier, which is what outlets now do declaratively, with selectors in markup and connection callbacks. The Stimulus reference treats it as a last resort when neither events nor outlets fit.
An outlet is phoning a particular colleague to ask them to do something: you need their number and they must pick up. An event is an announcement over the office speaker: whoever is in the room hears it, the speaker does not know who, and anyone who arrives later missed it.
- Outlets avoid coupling because the selector lives in HTML
- Stimulus replays dispatched events to listeners that connect later
- An outlet keeps pointing at the old instance after Turbo replaces the timer
- Events and outlets both require the controllers to share an element
- Two-way outlets between the timer and navigator are the cleanest design