Creating an Action
Explore how to create Stimulus actions that link DOM events to controller methods in a Rails app. Understand action descriptors, default event handling, and custom events to build interactive front-end behaviors.
We'll cover the following...
Connecting a DOM event to the controller
In Stimulus, an action connects a DOM event to the controller code that you want executed when that event happens. Like controllers, Stimulus actions are also defined using a data attribute in the markup: you add the attribute to the DOM element whose events you want to watch. In our case, that’s the div element we have styled as a button:
The new line defining the actions is data-action="click->day-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 little 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
click, followed by an arrow (->). The event can be any DOM event! - The second element is the name of the controller, spelled exactly the way the name is spelled