Stimulus. A modest JavaScript framework from Basecamp. Read the origin of Stimulus for the why they created this framework.
You can install from npm or from unpkg (stimulus.umd.js). Set up accordingly with you build system.
Let’s look at this HTML:
<div data-controller="hello">
<input data-target="hello.name" type="text">
<button data-action="click->hello#greet">Greet</button>
</div>
-
data-controller
to findhello_controller.js
. -
data-action="click->hello#greet"
to bindbutton
on eventclick
and runhello
controller’sgreet
method -
data-target="hello.name"
gets theinput
element inside hello controller’snameTarget
// hello_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "name" ]
greet() {
console.log(`Hello, ${this.name}!`)
}
get name() {
return this.nameTarget.value
}
}
static targets
adds 3 properties to the controller:
-
this.nameTarget
— 1st name target, error if name target not found -
this.nameTargets
— array of name targets -
this.hasNameTarget
— true if there is a name target
This can be further simplify if you’re using following Stimulus’s default events for elements.
- <button data-action="click->hello#greet">Greet</button>
+ <button data-action="hello#greet">Greet</button>
Default event for elements by Stimulus:
Element | Default Event |
---|---|
a | click |
button | click |
form | submit |
input | change |
input | type=submit click |
select | change |
textarea | change |
Controller and target beautifully connect HTML element and JavaScript. A very convenient way to organize JavaScript and keep HTML semantic and clean :+1:
Look at the document, there are so little things you need to learn.
Above examples are from Hello, Stimulus.