Using Gon in Stimulus

Let's learn to use Gon in Stimulus in this lesson.

We'll cover the following

Building up a controller

Now we can use the JavaScript global variable, which has the contents of our gon item, in our code by building up a Stimulus controller that reads from it. We need to add a little extra code to make sure TypeScript is okay with an unstructured global variable, since TypeScript is normally all about not being okay with unstructured global variables.

In Stimulus terms, we want a controller that will have one value (the id of the concert) and one target (the text that currently says “On Sale”). That’s three changes to the existing ERb file in app/views/schedules/show.html.erb. In keeping with the idea that Stimulus controllers should cover as little of the page as possible, we’ll set this one up inside the loop that displays concerts, where there’s an article tag for each concert, like so:

<article class="concert"
         data-text-toggle-target="concert"
         data-controller="sold-out-concert"
         data-sold-out-concert-id-value="<%= concert.id %>">

We’re adding the data-controller and the data-sold-out-concert-id-value attributes, associating the new controller with a data value. Since this tag is inside a loop, the ERb file will replicate this tag for each concert, and we’ll get a separate instance of the SoldOutConcertController for each one, each having its own concert-id value. Also, notice that this HTML tag is also a target for a different controller—that’s fine. It doesn’t bother Stimulus at all.

Next, we need to specify the target:

<div class="column is-size-4 is-one-fifth"
     data-sold-out-concert-target="label">
  On Sale
</div>

And with that, the controller is not very long at all:

Get hands-on with 1200+ tech skills courses.