DEV Community

loading...

Discussion on: Stimulus 2.0 Value change callbacks. What are they good for?

Collapse
leastbad profile image
leastbad

I am not being contrarian when I say that the valueChanged callbacks is my favourite feature of Stimulus 2.

One thing that might have escaped you so far is that the callbacks have two special properties. First, they fire before connect, meaning that you can use them to initialize your controller instance before it is even attached. That's already worth the price of admission. Second, the callback fires once if an initial value has been set, meaning that you can use it to "kick off" a behaviour, perhaps by setting a member variable that gets inspected by code in the connect method. Together, that makes this behaviour WILDLY powerful because it unlocks a whole category of new possibilities and next-level interactions.

I am clearly biased, but one of my favourite use cases so far is my stimulus-hotkeys controller.

What it does is use the values API to accept a JSON object that maps keyboard shortcuts to arbitrary methods on arbitrary Stimulus controllers, allowing you to create Gmail-style power-user shortcuts.

That's already cool, but with CableReady#set_dataset_property I can present users with the ability to specify their own custom key-mappings in realtime. If they change a mapped value, CableReady will take the current JSONB value for that user's key bindings and dynamically replace the data attribute on the hotkeys controller element. Thanks to the magic of the valueChanged callback, the changes take effect immediately.

My best advice is to shift from thinking about what valueChanged improves to what is possible that wasn't before.

Collapse
borama profile image
Matouš Borák Author

Hi leastbad, thanks for your comment! Unfortunately I have a very limited time to explore this topic further right now so I just wanted to tell you that if I sounded critical about the callbacks, I didn’t mean to, I am actually very excited about Stimulus 2, including the change callbacks. The fact that you can trigger a JS behavior solely via plain HTML is bewildering!

Also, this article was a purely theoretical exercise, and I hope I’ll diminish my ignorance a little bit once I get my feet wet on this in a real-world scenario. I’ll definitely explore the stuff you mentioned further. Thanks again!

Collapse
leastbad profile image
leastbad

It would be impossible to feel criticized, as I'm just a fellow user/traveller.