Goal
Show the before and after implementation of select2/formValidation/Turbolinks with the new modest js framework named stimulus
I am utilizing Rails as my framework here, but the setup really isn't about the framework. However, this demonstrates a good use case of server side rendered html without frontend framework separation.
I'll break this down into 2 steps:
- Implementation without Stimulus
- Implementation with Stimulus
Implementation without Stimulus
To accomplish this part I created a simple project. There are 2 files that are involved:
Erb File
In this file I am following the declarative/html5 data attributes way of using FormValidation as I prefer to keep the javascript as generic as possible.
CoffeeScript file
Here I am demonstrating:
- Select2 with normal, multiple, and tags with createTag as a way to constrain allowable input
- FormValidation on Select2
- FormValidation with custom callback on name field
- FormValidation using revalidation and hidden input change when select2 change event is triggered
- Removing Select2 from DOM before Turbolinks caches the page, which keeps double Select2's from showing up in the page
Implementation with Stimulus
To accomplish this part I utilized the master branch. This commit shows the diff of the conversion. Final demo app can be found here.
There are 3 files that are involved:
Erb File
The notable changes here to notice are the utilization of the data attributes of target, controller, and placeholder.
Application JS file
Not much to say about this file, as it is the basic wiring needed as the entry-point for Stimulus use.
Cars Controller JS file
Here I am demonstrating:
- Conversion into Stimulus from original CoffeeScript
- Additional storing of the selected items so they are preserved on forward and back buttons
Conclusions
I really like how this gives an easy way to leverage data attributes and hook easily into Javascript. While I didn't show it here, but will in another blog, Stimulus really shines when you can use it to describe the event handlers in the data attributes instead of having to deal with them in JavaScript.
I'd encourage people to give it a look. As can be seen here, you can easily hook into existing jquery libraries using it.
Thanks to this repo for getting me past a few initial humps.
Top comments (2)
Share your experience here as well.
discourse.stimulusjs.org/t/post-yo...
Hi,
Awaiting for your next blog.
Thanks.