You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
by manually adding a file in the controllers directory of your Rails application, e.g., app/javascript/controllers/my_feature_controller.js.
The controller file should define your Stimulus controller class:
// app/javascript/controllers/my_feature_controller.jsimport{Controller}from"stimulus";exportdefaultclassextendsController{connect(){// The connect action gets run as soon as an element connected to your controller is initializedconsole.log("MyFeatureController connected!");}}
In your HTML view, use the data-controller attribute to connect the controller to an element. The syntax is data-controller=<name-of-your-controller>:
<divdata-controller="my-feature"><!-- Your content here --></div>
Add Interactivity using data-action
In your controller, define a new method that will be triggered by an event (e.g. doSomething):
In your HTML view, use the data-action attribute to associate the action with an event. The syntax is data-action="<name-of-your-controller>#<nameOfTheAction>":
In your controller, use the targets property to define named references to HTML elements. You can then access those elements using this.<targetName>Target:
In your HTML view, use the data-target attribute to indicate where the element should be referenced. The syntax is data-target="<name-of-your-controller>.<target-name>:
In your controller, use the values property to define named references to dynamic values, and specify their datatype. They become accessible in your controller using this.<valueName>Value:
// app/javascript/controllers/my_feature_controller.js// ...exportdefaultclassextendsController{staticvalues={greeting: String};// ...initialize(){console.log("Initialized with greeting:",this.greetingValue);}}
In your HTML view, use the data-value attribute to set the dynamic value on the same element your controller is connected to. The syntax is data-<name-of-your-controller>-<name-of-the-value>-value="The value you want inside":
<divdata-controller="my-feature" data-my-feature-value="Hello from data-value!"><!-- Content here --></div>