Episodes

Resources

Download Source Code

Summary

# Terminal
yarn add stimulus_reflex

# Gemfile
gem 'stimulus_reflex'

# app/packs/application.js
import 'controllers'

# app/controllers/index.js
import { Application } from 'stimulus'
import { definitionsFromContext } from 'stimulus/webpack-helpers'
import StimulusReflex from 'stimulus_reflex'

const application = Application.start()
const context = require.context('controllers', true, /_controller\.js$/)
application.load(definitionsFromContext(context))
StimulusReflex.initialize(application)

# welcome/index.html.erb
<p>
  <div data-reflex="click->WelcomeReflex#greetings"
       data-room="public">Click Here</div>
  <%= @hello %>
</p>

<p>
  <div data-reflex='click->WelcomeReflex#increment'
       data-step="1"
       data-room="<%= request.user_agent %>"
       data-count="<%= @count.to_i %>">
    Increment <%= @count.to_i %>
  </div>
</p>

<p>
  <div data-controller="example"
       data-action='click->example#increment'
       data-step="1"
       data-room="<%= session.id %>"
       data-count="<%= @increment.to_i %>">
    Increment from Stimulus <%= @increment.to_i %>
  </div>
</p>

<p>
  <h2>Enter your name</h2>
  <input type="text" value="<%= @value %>" data-reflex="keyup->WelcomeReflex#say_hello">
  <h1><%= @name %></h1>
</p>

# app/reflexes/welcome_reflex.rb
class WelcomeReflex < StimulusReflex::Reflex
  def greetings # WelcomeGreetings#show
    @hello = "hello from stimulus reflex"
  end

  def increment
    @count = element.dataset[:count].to_i + element.dataset[:step].to_i
  end

  def say_hello
    @value = element.attributes[:value]
    @name = "Hello #{@value}!"
  end

  def from_stimulus(step)
    session[:count] = session[:count].to_i + step.to_i
    @increment = session[:count]
  end
end

# welcome_controller.rb
class WelcomeController < ApplicationController
  def index
    @increment = session[:count]
  end
end