data-reflex
attribute to declare a reflex without any code, or call the stimulate
method 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-reflex
attribute allows us to map an action on the client to code that will be executed on the server.[DOM-event]->[ReflexClass]#[action]
click
and change
are two of the most common events used to initiate Reflex actions, you can use mouseover
, drop
, play
and any others that makes sense for your application.scroll
, drag
, resize
or mousemove
. It's possible to use a debounce strategy to reduce how many events are emitted. data-step
and data-count
are used to pass data to the server. You can think of them as arguments.app/reflexes
folder. In this example, the increment
action is called and the count is incremented by 1. The @count
instance variable is passed to the template when it is re-rendered.stimulate
method.data-controller
and data-action
attributes, which can be changed if you have a conflict. There's no StimulusReflex-specific markup required:ApplicationController
, which is installed with StimulusReflex. It takes care of making your controller automatically inherit the stimulate
method:ApplicationController
and need to create a connect
method, make sure that the first line of your method is super.connect()
or else you can't call stimulate
.increment
method 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.preventDefault()
on that event, or else you will experience undesirable side effects such as page navigation or form submission.step
argument to our increment
Reflex 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 stimulate
method with arguments; there is no equivalent for Reflexes declared with data attributes.@count
instance variable in the controller action. When the page is first loaded, there will be no session[:count]
value and @count
will be nil
, which converts to an integer as 0... our initial value.@count
after fetching it from a persistent data store such as Postgres or Redis. To keep this example simple, we use Rails' session
to store our counter value.user
and users
are both valid and useful in different situations.app/javascript/controllers/application_controller.js
app/javascript/controllers/user_controller.js
app/reflexes/application_reflex.rb
app/reflexes/user_reflex.rb
bundle exec rails destroy stimulus_reflex user
your application_reflex.rb
and application_controller.js
will be preserved.