skip to content

Values, Classes & Outlets

Stimulus values, classes and outlets read typed state, CSS class names and other controllers from data attributes, with change callbacks. Interviewers ask how controllers talk to each other.

on this pageshow

explore

questions

6

In a Stimulus controller, how does static values turn data-<identifier>-<name>-value attributes into typed properties, and what happens when an attribute is missing?

level: middleimportance: must knowfreq 55%

answer

  1. Array, Boolean, Number, Object, String
  2. data-countdown-seconds-value -> this.secondsValue
  3. missing: your default, else [], false, 0, {}, ""
  4. { type: Number, default: 300 }
  5. the setter writes the attribute back

basics

~20 s

static values maps names to types; Stimulus then generates this.nameValue, which decodes data-<identifier>-<name>-value on the controller's element, a setter that writes it back, and hasNameValue. A missing attribute yields the declared default, or the type's default.

solid answer

~40 s

You declare `static values = { seconds: Number, warnAt: { type: Number, default: 300 } }`. For each entry Stimulus defines a getter `this.secondsValue` that reads `data-countdown-seconds-value` from the controller's own element and decodes it by type, a setter that encodes and writes the attribute, and `this.hasSecondsValue`. Decoding is type-specific: Number uses `Number()` after stripping underscores, Boolean is true for anything except `"0"` and `"false"` (so an empty attribute is true), Array and Object go through `JSON.parse`. A missing attribute returns the declared default, or the type's default: `[]`, `false`, `0`, `{}` or `""`. Because the getter reads the attribute every time, the HTML stays the single source of truth, and a Rails view can seed state with `data: { countdown_seconds_value: 1800 }`.

code

erb · 7 lines
erb
<%= tag.div id: "exam-countdown",
      data: { controller: "countdown",
              countdown_seconds_value: @attempt.seconds_left,
              countdown_warn_at_value: 300,
              countdown_running_value: [email protected]? } do %>
  <span data-countdown-target="display"></span>
<% end %>

go deeper

for a junior

Recall the static values declaration, the five types and the attribute name pattern data-identifier-name-value.

for a middle

Explain how each type decodes, which defaults apply when the attribute is missing, and that the setter writes the attribute back.

for a senior

Catch decoding traps such as empty Booleans, NaN numbers and the has<Name>Value caveat, and keep the server-rendered attribute the single source of truth.

for a principal

Use values as the contract between server views and client behaviour, deciding which state the server owns and which the browser may change.

## What values are A Stimulus **value** is a typed piece of controller state stored in a data attribute on the controller's element. The server renders it, the controller reads and writes it through generated properties, and the attribute stays the single source of truth. In an exam-practice app, a `countdown` controller needs the seconds left in the attempt and the point at which to warn the candidate, and both come straight from the Rails view. ## Declaring them ```javascript static values = { seconds: Number, warnAt: { type: Number, default: 300 }, running: { type: Boolean, default: true } } ``` - The **shorthand** form gives only a type: `Array`, `Boolean`, `Number`, `Object` or `String`. - The **expanded** form `{ type, default }` adds a default used when the attribute is missing. - If the default does not match the type (`{ type: Number, default: "5" }`), Stimulus throws an error naming the value when it reads the definition. - Names are camelCase in JavaScript and kebab-case in HTML: `warnAt` reads `data-countdown-warn-at-value`. ## The generated properties | property | effect | |---|---| | `this.warnAtValue` | reads and decodes the attribute, or returns the default | | `this.warnAtValue = 120` | encodes and writes `data-countdown-warn-at-value="120"` | | `this.warnAtValue = undefined` | removes the attribute, so the getter returns the default again | | `this.hasWarnAtValue` | true when the attribute is present; see the caveat below | The attribute must sit on the element carrying `data-controller="countdown"`. A value attribute on a child element is never read. ## How each type decodes | type | decoded from the attribute by | missing-attribute default | |---|---|---| | String | used as is | `""` | | Number | `Number(value)` after removing underscores, so `1_800` is 1800 | `0` | | Boolean | true unless the value is `"0"` or `"false"` (any case) | `false` | | Array | `JSON.parse`, then a type check | `[]` | | Object | `JSON.parse`, then a type check | `{}` | Three consequences come up in interviews: 1. **An empty Boolean attribute is true.** `data-countdown-running-value=""` decodes to `true`, which surprises anyone expecting HTML-style presence rules to mean false. 2. **Bad numbers are NaN, not errors.** `"30s"` decodes to `NaN`, so validate at the server. 3. **Bad JSON throws.** An Array value whose attribute holds an object raises a `TypeError` ("expected value of type "array""), and invalid JSON raises a parse error, both at the moment the getter is read. ## Writing values from Rails Rails' tag helpers dasherize `data:` keys and JSON-encode any value that is not a String, Symbol or BigDecimal, which lines up with the decoders: - `countdown_seconds_value: 1800` renders `data-countdown-seconds-value="1800"`; - `countdown_running_value: false` renders `"false"`, which decodes to `false`; - `countdown_sections_value: [1, 2, 3]` renders JSON that an Array value parses. ## The has<Name>Value caveat In Stimulus 3.2.2 the existential property returns true when the attribute is present **or** when the definition carries a default of its own. That covers the expanded `{ type, default }` form and a literal default such as `warnAt: 300`; only the bare type form `seconds: Number` depends on the attribute alone. So `hasWarnAtValue` is always true for the declaration above. To ask whether the server actually sent the attribute, declare that value with the bare type, or check `this.element.hasAttribute("data-countdown-warn-at-value")`. ## Review findings worth knowing - A value attribute placed on a child element instead of the controller element: the getter silently returns the default. - A `Boolean` meant to start false rendered as `data-countdown-running-value=""`: it decodes to true. - A `Number` read before the server sends it: the getter returns `0`, which can look like an expired timer rather than missing data. - A value renamed in the JavaScript but not in the ERB, or the reverse: the getter returns the default and nothing raises an error. ## Why the DOM holds the state Because the getter reads the attribute on every access and the setter writes it, the controller keeps no hidden copy. Whatever replaces or patches the element, whether a Rails re-render, a Turbo Stream, a morph refresh or your own code, the controller sees the current value on its next read. That is the "state in the HTML" rule in practice.

  • Why does hasWarnAtValue return true even though the view omitted the attribute?
    In Stimulus 3.2.2 the existential property is true when the attribute is present or when the definition carries its own default, which includes the expanded `{ type, default }` form. Only a bare type such as `warnAt: Number` makes it track the attribute alone; otherwise check `this.element.hasAttribute(...)`.
  • How do you hand a Stimulus Object value a Ruby hash from the view?
    Pass the hash in the `data:` option: `countdown_config_value: { warn_at: 300 }`. Rails JSON-encodes non-string data values, and the Object decoder runs `JSON.parse` and checks that the result is a plain object, so `this.configValue.warn_at` is 300.
  • What does this.secondsValue = undefined do?
    It removes `data-countdown-seconds-value` from the element. The getter then falls back to the declared default, or the type's default of 0 for a Number, and the change callback fires with that default.

  • Value attributes can sit on any element inside the controller
  • data-countdown-running-value="" decodes to false
  • A missing Number value reads as undefined
  • Values are copied into JavaScript once, so later attribute edits are ignored
  • Assigning this.secondsValue changes only a JavaScript field, not the HTML

Assumes Stimulus 3.2.2 (shipped by stimulus-rails 1.3.4 beside Turbo 8); the decoders and the has<Name>Value rule described here are read from its source.

open as a page

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?

level: seniorimportance: must knowfreq 45%

basics

~20 s

Use 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.

open as a page

In a Stimulus controller, what do static classes and properties such as this.warningClass give you over hard-coding CSS class names in JavaScript?

level: juniorimportance: should knowfreq 28%

basics

~10 s

static classes names logical styles; the view supplies the real CSS classes in data-<identifier>-<name>-class on the controller element, and the controller reads them as this.warningClass, this.warningClasses or hasWarningClass, so styling stays in the template.

open as a page

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%

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.

open as a page

In Stimulus, how does static outlets with a data-question-navigator-countdown-outlet selector give one controller another controller's instance, and when do outlet callbacks fire?

level: middleimportance: should knowfreq 35%

basics

~20 s

The host declares static outlets = ["countdown"] and puts a CSS selector in data-question-navigator-countdown-outlet; any element in the page matching it and carrying data-controller="countdown" becomes an outlet, reachable as this.countdownOutlet (the controller instance), with countdownOutletConnected/Disconnected callbacks.

open as a page

In a Stimulus controller, when does a callback such as secondsValueChanged(value, previousValue) run, and what does it receive on its first call?

level: middleimportance: should knowfreq 40%

basics

~20 s

secondsValueChanged runs once as the controller connects, before connect(), then after every change to data-countdown-seconds-value from any source. It gets the decoded new and previous values; the first previous value is the default, or undefined if the attribute is absent.

open as a page