In a Stimulus data-action descriptor, what do default events, key filters, @window and the :prevent, :stop and :once options change?
answer
- event->identifier#method plus extras
- textarea defaults to input, form to submit
- key filters only on keydown, keyup, keypress
- @window or @document moves the listener
- :prevent/:stop/:self vs :once/:passive/:capture
basics
~20 sA descriptor may omit the event for common elements (textarea means input, form means submit), filter keyboard events (keydown.ctrl+enter), listen on window or document (@window), and add options: :prevent and :stop call preventDefault or stopPropagation, :once passes once to addEventListener.
solid answer
~40 sThe full grammar is `event.filter@target->identifier#method:option`. If the event is omitted Stimulus uses the element's default: `click` for links and buttons, `input` for text inputs and textareas, `change` for selects, `submit` for forms, `toggle` for details. Key filters such as `keydown.esc` or `keydown.ctrl+enter` apply only to `keydown`, `keyup` and `keypress`. `@window` or `@document` installs the listener on that global object, and Stimulus unbinds it when the controller disconnects. Options come in two families: `:capture`, `:once`, `:passive` and `:!passive` become `addEventListener` options, while `:prevent`, `:stop` and `:self` are Stimulus filters that call `preventDefault()`, call `stopPropagation()`, or skip events from descendants. Several descriptors for the same event on one element run left to right.
code
html · 9 lines<form action="/job_postings" method="post"
data-controller="character-counter"
data-action="keydown.ctrl+enter->character-counter#submit">
<textarea name="job_posting[description]" maxlength="2000"
data-character-counter-target="input"
data-action="character-counter#update"></textarea>
<p><span data-character-counter-target="count">0</span> / 2000</p>
<a href="#tips" data-action="character-counter#showTips:prevent">Writing tips</a>
</form>go deeper
Recall the arrow syntax and the default events for button, textarea, select and form so you can write short descriptors confidently.
Explain which options go to addEventListener and which are Stimulus filters, and why key filters only work on keyboard events.
Use @window and @document descriptors instead of hand-written global listeners so cleanup is automatic, and reason about ordering and stopImmediatePropagation between descriptors.
Weigh declarative descriptors in markup against listener code in controllers for readability and cleanup, and when a custom action option is worth registering app-wide.
## The descriptor grammar A Stimulus **action descriptor** is the string inside `data-action`. Its full shape is: ``` event.keyFilter@globalTarget->identifier#method:option:option ``` Only `identifier#method` is always required. Each optional piece changes either **when** the method runs or **what Stimulus does to the event first**. `data-action` holds a space-separated list of descriptors, so one element can route several events, or the same event to several controllers. ## Default events When the event name is left out, Stimulus picks one from the element: | element | default event | |---|---| | `a`, `button` | `click` | | `input` (any type except submit) | `input` | | `input type="submit"` | `click` | | `textarea` | `input` | | `select` | `change` | | `form` | `submit` | | `details` | `toggle` | So a job-posting description field can say `data-action="character-counter#update"` and update on every keystroke. On an element outside this table, such as a `div`, a descriptor without an event cannot be built: Stimulus catches the "missing event name" error internally and simply drops the action, with nothing in the console. ## Key filters A **key filter** follows the event after a dot: `keydown.esc->modal#close`. - It applies only to `keydown`, `keyup` and `keypress`. On any other event the dot is folded into the event name, so `click.enter` listens for an event literally named `click.enter` and never fires. - Built-in names include `enter`, `tab`, `esc`, `space`, `up`, `down`, `left`, `right`, `home`, `end`, `page_up`, `page_down`, the letters `a`-`z` and the digits `0`-`9`; more can be added through a custom schema's `keyMappings`. - **Modifiers** `meta`, `ctrl`, `alt` and `shift` combine with a plus: `keydown.ctrl+enter`. Modifiers must match exactly, so `keydown.enter` ignores Ctrl+Enter. - Mouse events take a modifier prefix instead: `ctrl+click->listing#openInTab`. ## Global targets `resize@window->character-counter#layout` or `turbo:before-cache@document->character-counter#reset` installs the listener on `window` or `document` rather than the element. The method still runs on the controller instance that declared it. When that controller disconnects, Stimulus drops its binding and removes the global listener once no other binding shares it, which avoids the leak a hand-written `window.addEventListener` in `connect()` causes. ## Options: two families Options are appended with colons, and a leading `!` sets an option to false: 1. **DOM listener options**, passed straight to `addEventListener`: `:capture`, `:once`, `:passive` and `:!passive`. 2. **Stimulus filters**, run before the method: `:prevent` calls `event.preventDefault()`, `:stop` calls `event.stopPropagation()`, `:self` invokes the method only when the event's target is the element carrying the descriptor. Filters run only when the binding is about to fire: a `keydown.enter->search#submit:prevent` action does not cancel other keys. You can add your own filter with `application.registerActionOption(name, callback)`; returning `false` from the callback blocks the call. ## Ordering and the event object - Descriptors for the same event on one element run **left to right**. - Calling `event.stopImmediatePropagation()` inside a method skips the descriptors to its right. - The method receives the DOM event, extended with `params` from action parameters. ## Mistakes worth catching in review - **A key name outside the mapping**, such as `keydown.return`, is not ignored: when an unmodified keydown reaches the action, Stimulus throws a "contains unknown key filter" error. Add custom names through `keyMappings`. - **Methods named after the event** (`click`, `handleClick`) say nothing about behaviour; the Stimulus docs recommend names that state the effect, such as `copy` or `showTips`. - **`:prevent` used where `:stop` was meant**, or the reverse: one cancels the browser's default action, the other stops the event travelling to ancestors, and neither does both. - **A descriptor for a controller that is not an ancestor** is never bound, so it fails silently. ## A character counter that submits on Ctrl+Enter On a job-board posting form, the textarea updates a counter through its default `input` event, and the form submits on Ctrl+Enter. The form element carries `keydown.ctrl+enter->character-counter#submit`; keystrokes inside the textarea bubble up to it, the filter discards everything except Ctrl+Enter, and `submit()` calls `this.element.requestSubmit()` so the normal submit path, Turbo's included, still runs.
- How would you add an option such as :open that routes a details toggle only when it opens?Register it on the application: `application.registerActionOption("open", ({ event, value }) => event.type != "toggle" || event.target.open == value)`. The callback receives the option name, its value (`true` for `:open`, `false` for `:!open`), the event, the element and the controller, and returning `false` blocks the method.
- Two descriptors on one button handle click. How does the first stop the second?Descriptors for the same event run left to right in attribute order. Calling `event.stopImmediatePropagation()` in the first method sets a flag Stimulus checks between bindings, so the descriptors to its right are skipped, and the browser stops any later listeners too.
- Does keydown.enter->search#submit:prevent cancel every key the user types?No. Stimulus checks the key filter before running filters such as `:prevent`, so `preventDefault()` is called only for Enter; other keys pass through untouched because the binding never fires for them.
- :prevent stops the event from reaching listeners on ancestor elements
- A key filter like .enter also works on click actions
- Every data-action descriptor must spell out its event name
- Listeners added with @window stay attached after the controller disconnects
- Several descriptors on one element run in no guaranteed order
- :once is a Stimulus filter that counts calls itself