Creating an Action
Let's learn to create Stimulus actions, which link a DOM event to a controller.
We'll cover the following...
Connecting a DOM Event to the Controller
In Stimulus, an action is what connects a DOM event to the controller code that we want to execute when that event occurs. Like controllers, Stimulus actions are defined using a data attribute in the markup; we add the attribute to the DOM element whose events we want to watch. In our case, we want to add a button that says “Hide”:
<div class="button is-primary js--day-button"data-action="click->day-toggle#toggle"><span class="js--button-text">Hide</span></div>
The new line defining the actions is data-action="click->favorite-toggle#toggle"
. The data-action
is the attribute name that signals to Stimulus that an action is being defined. The value of the data-action
attribute is a mini-language to define the connection between the event and the code.
The mini-language, which Stimulus calls an action descriptor, has three parts:
-
The first element is the name of the event being watched for, which in our case is a
click
, followed by an arrow (->
). -
The second element is the name of the controller, spelled ...