Adding Our First Controller

Add a controller to the application in this lesson.

How controllers work

The bulk of your Stimulus code will go through a controller, which is similar to your Rails controller in that it’s where the responses to events are stored, but there’s much less structure and expectations around a Stimulus controller than a Rails controller.

To invoke a controller, you add an attribute named data-controller to a DOM element on your page. The value of the attribute is the name of the controller. If the controller’s name is more than one word, you 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 you want dispatched to the controller need to happen inside the controller’s DOM element. Any elements that you 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 make a working version of the show/hide button for each day, so we want to press the button, hide the concerts for that day, and change the text of the button. This means our controller needs to be attached to a DOM element that encompasses both the button and all the concerts for that day.

Happily, we have such a DOM element. It’s the one in app/views/schedules/show.html.erb inside the loop that we’ve already given the DOM class of day-body to. We want to make it look like this:

<section
  class="day-body"
  id="day-body-<%= schedule_day.day.by_example("2006-01-02")%>"
  data-controller="day-toggle">

We are adding the DOM attribute data-controller and giving it the value day-toggle. By itself this doesn’t do much. But when the page is loaded, Stimulus will look for a matching controller. Using convention over configuration, that controller should be in the file app/javascript/controller/day_toggle_controller.ts.

Here’s a basic controller that doesn’t do anything yet:

Create a free account to view this lesson.

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