This article was originally published on is now available with a discount up to 50% 🤑
if you want to learn more.
Passing params to actions
Sometimes you need to pass some attribute to a certain method. That's easy and works like this:
<div data-controller="theme">
<button data-action="theme#update" data-theme-value-param="dark">
Lights Off
</button>
</div>
Then the update method will look like this:
update({ params: { value } }) {
this.#setClass(value);
}
It follows this structure data-[identifier]-[param-name]-param. It can take any type for a value from a String, Number to an Object and a Boolean. Refer to the .
Nested Scopes
Each controller in Stimulus operates within its own isolated scope. This means it can only interact with targets defined in its immediate context. Parent controllers cannot access targets from nested child controllers, and vice versa.
Wanna see code? I heard you like tabs in your tabs:
<div data-controller="tabs">
<div data-tabs-target="panel">
<!-- This panel is found by the parent tabs controller -->
</div>
<div data-controller="tabs">
<div data-tabs-target="panel">
<!-- This panel is only found by the nested tabs controller -->
</div>
</div>
</div>
This might be something you stumbled upon by accident (or frustration?), but it is still a good feature to know about.
shouldLoad method
Do you want certain features to only work on mobile devices, or maybe you have some special functionality just for touch devices? You can conditionally load a controller with shouldLoad. Simply like this:
export default class extends Controller {
static get shouldLoad() {
return window.innerWidth <= 768 && "ontouchstart" in window
}
}
This controller won't be registered and loaded at all. So there won't be any creation of the controller instance. This is different from, say adding return false to your connect lifecycle method, where an instance is created.
afterLoad method
Sometimes you need to run some setup code right after a controller is registered, regardless of whether any elements are using it yet (connected). afterLoad is perfect for this.
Again, a code snippet might help:
export default class extends Controller {
static afterLoad(identifier, application) {
// anything you need to get done here
}
}
Honestly, I have thought about afterLoad() for a fair bit and haven't come up with a real use-case for it. I've simply included as it's semi-related to shouldLoad() and it's good to know it's there. So if you find a use-case for it, please let me know below.
SOCIAL SHARE CARD GENERATOR