data-reflexattribute to declare a reflex without any code, or call the
stimulatemethod inside of a Stimulus controller. We can use these techniques interchangeably, and both of them trigger a server-side "Reflex action" in response to users interacting with your UI.
data-reflexattribute allows us to map an action on the client to code that will be executed on the server.
data-countare used to pass data to the server. You can think of them as arguments.
app/reflexesfolder. In this example, the
incrementaction is called and the count is incremented by 1. The
@countinstance variable is passed to the template when it is re-rendered.
ApplicationController, which is installed with StimulusReflex. It takes care of making your controller automatically inherit the
incrementmethod on our controller. In this example, we pass two parameters: the first one follows the format
[ReflexClass]#[action]and informs the server which Reflex action in which Reflex class we want to trigger. Our second parameter is an optional argument that is passed to the Reflex action as a parameter.
stepargument to our
incrementReflex action. We're also now switching to using the Rails session object to persist our values across multiple page load operations. Note that you can only provide parameters to Reflex actions by calling the
stimulatemethod with arguments; there is no equivalent for Reflexes declared with data attributes.
@countinstance variable in the controller action. When the page is first loaded, there will be no
nil, which converts to an integer as 0... our initial value.
usersare both valid and useful in different situations.