The connect
method of Stimulus and this.element
is what we mostly need.
Comparisions
Stimulus and Svelte having totally different strengths:
Svelte holds JS and html in one file and is a, as handy as mighty, tool for making complex things or user-interactions super easy. It is able for running conditions or loops in the html template, like known in rails views.
Stimulus, built from the rails team, is a «modest» library for connecting js to the rails-views! Its the part that we previously built with cumbersome initializers or jQuery.
Thats the difference!
Without Stimulus there would be failing one part of the symphony.
Setup
$ npm i @hotwired/stimulus vite-stimulus-initializer
application.js
import { initStimulus } from "vite-stimulus-initializer";
const controllers = import.meta.glob('../javascript/**/*-controller.js', { eager: true })
initStimulus(controllers, 2, { debug: true, exclude: ['components', 'views'], folderSeparator: '-' })
See naming options on vite-stimulus-initializer
Test Code
javascript/controllers/hello-controller.js
By the filename, the controller will be hooking on any element with data-controller="admin-hello"
.
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
connect() {
// connect fires after the controller has found a corresponding element.
console.log("Stimulus is connected", this.element)
}
static targets = [ "name" ]
greet() {
const element = this.nameTarget
const name = element.value
console.log(`Hello, ${name}!`)
}
}
any view in .haml
%div{ 'data-controller' => 'admin-hello' }
%input{:type => "text", 'data-admin-hello-target' => 'name'}/
%button{ 'data-action' => "click->admin-hello#greet" } Greet
same in html.erb
<div data-controller="admin-hello">
<input data-admin-hello-target="name" type="text">/</input>
<button data-action="click->admin-hello#greet">Greet</button>
</div>
by loading this you should see a «Stimulus is connected» in the console. Writing «John» in the input and clicking the button should print out a «Hello John!» on the console.
⚠️ Together with turbo you may see a double «Stimulus is connected» on the console (connect fires 2 times). Based on my Tests it is first firing on the old, element then turbo replaces this and then its firing on the new element, so it should't matter and the new element is not a double-initialized.
Continue with Stimulus Handbook
Good luck!
Top comments (0)