⚠️ This lesson is retired and might contain outdated information.

Fire a Stimulus Controller Action on a Click Event

Ian Jones
InstructorIan Jones
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 2 years ago

In our Stimulus App, we change the connect method to a greet action (this method name can be anything.

We then wire that action up to our HTML button by adding data-action to it and passing the function that we want to fire, in this case, its click->example#greet.

Instructor: [0:00] Here, we have a stimulus controller named example_controller. In our html, we're wiring up our controller to this div. Instead of firing console.log('Hello') on connect, we're going to change this to an action called greet.

[0:20] The next thing we need to do is jump over to our html. We need to add a button. We'll give it a text of Greet. To wire up our greet action from our controller, we will add data-action="click." This is the DOM event that we're using.

[0:53] We tell stimulus to fire our greet method in our example_controller. When we refresh, and we open up our developer tools, hop over to the console. When we click Greet, we'll get Hello.

[1:09] To wrap up, all we did was create a method called greet on our controller class. We added a button to our html with an attribute of data-action and a value of click, which is the DOM event we want to fire our action on. Our action is our example_controller's greet method.

egghead
egghead
~ 2 hours ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today