Skip to content

Instantly share code, notes, and snippets.

@firedev
Created March 24, 2023 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save firedev/0206221cadb0428f0f134707dc9e992f to your computer and use it in GitHub Desktop.
Save firedev/0206221cadb0428f0f134707dc9e992f to your computer and use it in GitHub Desktop.
Stimulus to Apline.js for Hotwire

When replacing Stimulus with Alpine there are some things we need to consider. I propose to follow rails conventions as close as possible.

  1. 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
  1. x-naming. Stimulus uses kebab, i.e. select_weekly_controller becomes data-controller="select-weekly". Let’s do the same, except data identifiers should be valid JS in Alpine, I think PascalCase 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"
  1. 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 is data-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' ]
}
  1. 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"
  1. Confirmation. Turbo has data-turbo-confirm I am considering an x-confirm directive.

  2. Interesting reading https://brianschiller.com/blog/2021/11/05/alpine-stimulus-js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment