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 robust browser support, the gem also includes the requisite polyfills for Stimulus. We also include these features without the need for Webpack or any other JavaScript build tooling. As such, you can use this gem and the Stimulus framework as far back as Rails 4.2.

For a detailed explanation of how to use Stimulus, refer to their documentation. The only differences are around the JavaScript syntax. In their documentation, they presume you are working in a Webpack environment. We are not. Instead, we use the sprockets-es6 gem to allow us to transpile ES6 into ES5. So, any of your application's Stimulus controllers need to use the *.es6 file extension. Moreover, there are some small differences in the controller class syntax. In the Stimulus documentation, they provide this "hello, world" example:

// hello_controller.js

import { Controller } from "stimulus"

export default class 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:

// hello_controller.es6

class HelloController extends Stimulus.Controller {
  static get targets() {
    return [ "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>