StimulusJS: values/classes
This course covers how Stimulus controllers read configuration from data attributes through static values and static classes, using controllers from one application. It explains why typed values replace raw dataset strings, the shorthand and full object declaration forms, and each type's built-in default. It walks through the type coercion rules in stimulus-rails 1.3.4, accessors that read and write the DOM attribute immediately, and xxxValueChanged callbacks that fire on change and during connect. It ends with static classes, which keep CSS class names in the HTML.
What you'll learn
- ✓Declaring values with the shorthand or the full type and default object
- ✓Built-in fallbacks per type and when to write an explicit default
- ✓The coercion rules for Boolean, Number, String, Array and Object values
- ✓Reading and writing this.xxxValue and what hasXxxValue reports
- ✓Using xxxValueChanged callbacks as the render step, with guards
- ✓Declaring static classes to keep CSS class names in the template
Why values exist: reading config out of the DOM
A Stimulus controller's element can carry configuration in plain data-* attributes before static values enters the picture. this.element.dataset.dismissAfter reads a string, always a string, with no declared name to check typos against and no type to convert it into. This app's flash controller…
Read the full lesson free →Curriculum
7 lessonsWhy values exist: reading config out of the DOM
Why static values exists: dataset always returns strings, while a declared Number value arrives already converted.
Declaring values: shorthand vs. the full object form
The shorthand type constructor versus the full type and default object, with all five value types in use.
Defaults: explicit values vs. each type's built-in fallback
Each type's built-in fallback, when an explicit default is needed, and why a missing attribute differs from an empty one.
Type coercion: the exact rules Stimulus applies
The reader functions in stimulus-rails 1.3.4, including the Boolean rule where only "0" and "false" become false.
Reading and writing values: this.xxxValue as a live accessor
How this.xxxValue reads and writes the DOM attribute immediately, and why hasXxxValue is always true with a declared default.
xxxValueChanged callbacks: the value is the state, the callback is the render
How xxxValueChanged callbacks fire on each attribute change and once before connect(), and how controllers guard them.
static classes, and putting it together
How static classes turns space-separated class names from data attributes into arrays, shown in the confirmation modal.