Stimulus is a «modest» Lightwight Library, created by the rails team that connects html and JavaScript. JS and html are in separated files.
Links
Stimulus-docs/Installation/hello-stimulus
Prerequisites
Setup
$ npm i @hotwired/stimulus stimulus-vite-helpers
see: GitHub/stimulus-vite-helpers
frontend/controllers/index.js
import { Application } from '@hotwired/stimulus'
import { registerControllers } from 'stimulus-vite-helpers'
const application = Application.start()
const controllers = import.meta.globEager('./**/*_controller.js')
registerControllers(application, controllers)
frontend/entrypoints/application.js
import '../controllers'
Test Code
see: Stimulus Docs/is this thing on?
frontend/controllers/hello_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
connect() { // => «connect» method is similar to initialize method in a ruby-class
console.log("Hello, Stimulus!")
}
static targets = [ "name" ]
greet() { // => doesnt matter for now, but later for the view
const element = this.nameTarget
const name = element.value
console.log(`Hello, ${name}!`)
}
}
any view .haml
%div{"data-controller" => "hello"}
%input{"data-hello-target" => "name", :type => "text"}/
%button{"data-action" => "click->hello#greet"} Greet
view in .html.erb
<div data-controller="hello">
<input data-hello-target="name" type="text">/</input>
<button data-action="click->hello#greet">Greet</button>
</div>
=> Reload page and you should see «Hello Stimulus!» in Browser/developer Console.
=> type «User» in the input, click «Greet» button and you should see «Hello User!» in the Browser/Developer Console
Top comments (0)