When replacing Stimulus with Alpine there are some things we need to consider. I propose to follow rails conventions as close as possible.
- Naming of files. Snake case, same file name. In Stimulus everything ends in
_controller
btw.
legos/
select.rb
select.html.slim
select.js
select_weekly.rb
select_weekly.html.slim
select_weekly.js
x-naming
. Stimulus uses kebab, i.e.select_weekly_controller
becomesdata-controller="select-weekly"
. Let’s do the same, except data identifiers should be valid JS in Alpine, I thinkPascalCase
is the best.
// legos/select_weekly.js
Alpine.data('select-weekly') ❌
Alpine.data('select_weekly')
Alpine.data('selectWeekly')
Alpine.data('SelectWeekly') ✅
// legos/select_weekly.html.slim
div x-data="select-weekly" ❌
div x-data="select_weekly"
div x-data="selectWeekly"
div x-data="SelectWeekly" ✅
- Explicit “targets”. with Stimulus you explicitly specify what you expect the component to interact with.
Targets become
<controller>-target="name"
i.e. you know there isdata-select-weekly-target="input"
somewhere. We need something like this for Apline.
// app/javascript/controllers/select_weekly_controllers.js
export default class extends Controller {
static targets = [ 'input', 'option' ]
}
- Explicit Methods, Stimulus is very explicit in this regard, easy to tell what’s being called.
input data-action="select-weekly#changed invalid->select-weekly#setMessage"
-
Confirmation. Turbo has
data-turbo-confirm
I am considering anx-confirm
directive. -
Interesting reading https://brianschiller.com/blog/2021/11/05/alpine-stimulus-js