Hotwire: custom Stimulus
This course covers how Stimulus controllers in one Rails application communicate without holding references to each other. It starts with two controllers attached to one element, then the inherited dispatch() method and its defaults for target, detail and bubbling. It explains why event names get the controller identifier as a prefix and how to change or turn off that prefix. It then covers same-element listeners, @window listeners for custom and native events, and several action descriptors on one element.
What you'll learn
- ✓Attaching several controllers to one element with data-controller
- ✓Firing custom events with this.dispatch() and its defaults
- ✓The identifier:eventName convention and the prefix option
- ✓Listening for events dispatched on the same element
- ✓Using @window for custom and native browser events
- ✓Combining several action descriptors in one data-action
Multiple controllers, one element
data-controller isn't limited to one identifier. Write two, separated by a space, and both controllers attach to the same element independently, each with its own targets, values and lifecycle. Neither knows the other exists unless something explicitly connects them. This app's real challenge UI,…
Read the full lesson free →Curriculum
7 lessonsMultiple controllers, one element
Attaching two controllers to one element with data-controller, each keeping its own targets, values and lifecycle.
this.dispatch(): a controller's own custom events
How the inherited dispatch() method fires custom events, with defaults for target, detail, bubbling and prefix.
The event name convention: identifier:eventName
Why dispatch("search:open") fires ui--navbar:search:open, and how the prefix option replaces or disables the identifier.
Same-element listening: how irb tells hints an attempt failed
How a same-element data-action lets execution--hints catch the failed event from execution--irb and update the solution gate.
Going global: @window, and native events too
Using @window to catch bubbling custom events and native clicks across unrelated elements, including click-outside-to-close.
One element, multiple action descriptors
Writing several space-separated descriptors in one data-action, routing triggers to one method or to separate methods.
Putting it together: an event's full journey
Tracing two events from dispatch to listener, plus a challenge that reimplements the prefix rule in Ruby.