Adding Our First Controller

Add a controller to the application in this lesson.

How controllers work

The first thing we’re going to do with Stimulus is, create a “Show/Hide” button that will toggle the contents of the favorite concerts block on our page.

The bulk of our Stimulus code will go into a controller. Similar to our Rails controller, a Stimulus controller is where we store responses to events. But, Stimulus controllers are different in that they have less structure and fewer expectations than a Rails controller.

To invoke a controller, we add an attribute named data-controller to a DOM element on our page. The value of the attribute is the name of the controller. If we add an attribute data-controller="toggle", then Stimulus attaches it to a ToggleController, which it expects will be at controllers/toggle_controller.ts (or .js).

If the controller’s name is more than one word, we use dash case, so it would be fancy-color, not fancyColor. The controller has the same scope as the DOM element it’s attached to. This means that any events we want dispatched to the controller need to happen inside the controller’s DOM element. Any elements we designate as targets for the controller also need to be inside the controller’s DOM element.

Creating a controller for show/hide

In our app we want to have a “Show/Hide” button, which should include the ability to press the button, hide the list of favorite concerts, and change the text of the button. This means our Stimulus controller needs to be attached to a DOM element that encompasses both the button and all the favorite concerts.

We have such a DOM element: the parent <section> element in our favorites/_list partial. Let’s give it a data-controller attribute:

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy