DEV Community

Cover image for Rails 6, Stimulus  events
Ronak Bhatt for Main Street

Posted on • Updated on

Rails 6, Stimulus events

An action is a connection between:

  • a controller method
  • the controller’s element
  • a DOM event listener

gallery_controller.js

// controllers/gallery_controller.js
import { Controller } from "stimulus"

export default class extends Controller {
  next(event) {
    alert("Justclick !!! :")
  }
}
Enter fullscreen mode Exit fullscreen mode
View File Setup
<div data-controller="gallery">
  <button data-action="click->gallery#next">…</button>
</div>
Enter fullscreen mode Exit fullscreen mode
Descriptors

The data-action value click->gallery#next is called an action descriptor. In this descriptor:

  • click is the name of the DOM event to listen for
  • gallery is the controller identifier
  • next is the name of the method to invoke
The full set of these shorthand pairs is as follows:

Screenshot 2020-10-27 at 6.24.03 PM

I hope that helps someone. Thanks :).

Thanks for reading. 🙂

I’d love to hear thoughts or comments around this. Feel free to email me at ronakabhattrz@gmail.com or hit me up on twitter, @ronakabhattrz .

Discussion (0)