A Little More Stimulus

Let's use Stimulus to build some more features!

We'll cover the following

Now that we’ve seen the basics of Stimulus, let’s build the toggle based on the calendar dates that we did in the Going Generic section, and while we’re here, let’s make the search field work, too. Both can be done with very short Stimulus controllers.

The planning in adding Stimulus features involves where to place the controller, the targets, and the actions. We’ll do this as two separate controllers: one for the calendar dates, and one for the text filter. Both of these controllers act on the entire page—there’s a filter in the header part, but the result is in the body of the page. The controller needs to encompass both parts, so it makes sense to declare both controllers in the section tag that encompasses the whole page:

<section data-controller="calendar-toggle text-toggle"
         data-calendar-toggle-hidden-class="is-hidden"
         data-calendar-toggle-selected-class="has-text-danger"
         data-text-toggle-hidden-class="is-hidden">

We can declare the two controllers together, space delimited. We’ve also got a couple of classes to declare.

The calendar date toggle needs one action, which happens when we click on one of the dates. Like the generic version, it’ll use DOM IDs to associate the date in the header with the date in the body, so we don’t actually need any targets. It turns out to be a little easier to manage this interaction via DOM IDs than to use targets, because of the way the date headers and the date bodies are laid out on the page. The action looks like this:

<div class="column has-text-centered js--schedule-day"
     data-action="click->calendar-toggle#toggle"
     id="day-toggle-<%= schedule_day.day.by_example("2006-01-02") %>">
  <%= schedule_day.day.by_example("Jan 2") %>
</div>

We’ve got the click action, the controller name, and the name of the method we want to invoke.

The controller itself is short:

Get hands-on with 1200+ tech skills courses.