Skip to main content

Stimulus Integration

This gem integrates the Stimulus.js framework. For those unfamiliar, Stimulus describes itself as:

Stimulus is a JavaScript framework with modest ambitions. It doesn’t seek to take over your entire front-end—in fact, it’s not concerned with rendering HTML at all. Instead, it’s designed to augment your HTML with just enough behavior to make it shine. Stimulus pairs beautifully with Turbolinks to provide a complete solution for fast, compelling applications with a minimal amount of effort.

Stimulus fits in very nicely with the way that we write web applications. This gem uses Stimulus to manage the app navigation expand/collapse behavior. The gem also provides to your application an initialized stimulus instance, with which you can register any of your application's Stimulus controllers.

For detailed instructions on using Stimulus, please refer to the official documentation. The main difference in our setup lies in the JavaScript syntax. The documentation assumes you're working in an environment that supports ES module import syntax. However, since our application still uses Sprockets, we load Stimulus as a UMD (Universal Module Definition) module instead.

In the "Hello, World" example below, you'll see the difference between using the modern import syntax and the syntax required in our environment.

This is the official documented way of declaring a stimulus controller.

import { Controller } from "stimulus"

class HelloController extends Controller {
  static targets = [ "name", "output" ]

  greet() {
    this.outputTarget.textContent =
      `Hello, ${this.nameTarget.value}!`
  }
}

This is how you would write this controller in our environment:

class HelloController extends Stimulus.Controller {
    static targets = [ "name", "output" ]

    greet() {
    this.outputTarget.textContent =
      `Hello, ${this.nameTarget.value}!`
  }
}

You will then need to be sure to register your HelloController with the stimulus instance that this gem provides:

// application.js

//= require hello_controller
stimulus.register('hello', HelloController)

Wired up in this way, you could then use this controller in your HTML precisely as their documentation describes:

<!--HTML from anywhere-->
<div data-controller="hello">
  <input data-target="hello.name" type="text">

  <button data-action="click->hello#greet">
    Greet
  </button>

  <span data-target="hello.output">
  </span>
</div>