Advanced Use
How to get the most out of StimulusReflex
ActionCable
StimulusReflex leverages Rails ActionCable. Understanding what Rails provides out of the box will help you get the most value from this library.
Performance
ActionCable emits verbose log messages. Disabling ActionCable logs may improve performance.
ActionCable.server.config.logger = Logger.new(nil)
Rooms
You might find the need to restrict communication to a specific room. This can be accomplished in 2 ways.
Passing the room name as an option to
register
.
export default class extends Controller {
connect() {
StimulusReflex.register(this, { room: 'ExampleRoom12345' });
}
}
Setting the
data-room
attribute on the StimulusController element.
<a href="#"
data-controller="example"
data-reflex="click->ExampleReflex#do_stuff"
data-room="12345">
Setting room in the body with a data attribute can pose a security risk. Consider assigning room when registering the Stimulus controller instead.
Stimulus Controllers
Render Delay
An attempt is made to reduce repaint jitter when users trigger several updates in succession.
You can control how long to wait prior to updating the DOM - think debounce. Simply set the renderDelay
option in milliseconds when registering the controller.
export default class extends Controller {
connect() {
StimulusReflex.register(this, { renderDelay: 200 });
}
}
Reflexes
Server side reflexes inherit from StimulusReflex::Reflex
and hold logic responsible for performing operations like writing to your backend data stores. Reflexes are not concerned with rendering because rendering is delegated to the Rails controller and action that originally rendered the page.
Properties
connection
- the ActionCable connectionchannel
- the ActionCable channelrequest
- anActionDispatch::Request
proxy for the socket connectionsession
- theActionDispatch::Session
store for the current visitorurl
- the URL of the page that triggered the reflexelement
- a Hash like object that represents the HTML element that triggered the reflex
element
element
The element
property contains all of the Stimulus controller's DOM element attributes as well as other properties like checked
and value
.
Here's an example that outlines how you can interact with the element
property in your reflexes.
<checkbox id="example" label="Example" checked
data-reflex="ExampleReflex#work" data-value="123" />
class ExampleReflex < StimulusReflex::Reflex
def work()
element[:id] # => the HTML element's id attribute value
element.dataset # => a Hash that represents the HTML element's dataset
element[:id] # => "example"
element[:checked] # => true
element[:label] # => "Example"
element["data-reflex"] # => "ExampleReflex#work"
element.dataset[:reflex] # => "ExampleReflex#work"
element["data-value"] # => "123"
element.dataset[:value] # => "123"
end
end
Last updated
Was this helpful?