Stimulus

Stimulus. A modest JavaScript framework from Basecamp. Read the origin of Stimulus for the why they created this framework.

Install

You can install from npm or from unpkg (stimulus.umd.js). Set up accordingly with you build system.

Example

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 find hello_controller.js.
  • data-action="click->hello#greet" to bind button on event click and run hello controller’s greet method
  • data-target="hello.name" gets the input element inside hello controller’s nameTarget
// 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 👍

Look at the document, there are so little things you need to learn.

Above examples are from Hello, Stimulus.