Communicating between Stimulus controllers using custom events
Last updated on December 20, 2021
There isn't a lot of information online about how you should go about communicating between Stimulus controllers. There is one issue on Github which explains how you should do it using this.application.getControllerForElementAndIdentifier but I was not able to make it work using this approach.
In this article, I will teach you how to achieve this using another technique - create a custom event in one controller which triggers an action in another controller.
In your stimulus controller, you can create a custom event using:
1const event = new CustomEvent("update-map")2window.dispatchEvent(event)
Let's break down this code.
- You define a constant event using the CustomEvent constructor. This object represents an event which will take place in the DOM. The parameter represents the name of the event. You can name your event however you like to explain your own unique situation. You can also pass a second parameter if you wish to include additional information as part of your event. You can read more about it here.
- Dispatch the event to the DOM and invoke the affected EventListeners (in our case, the data-action)
In your HTML, define the following data-action inside your receiving Stimulus controller.
Level up your web development skills
Get articles, guides and interviews right in your inbox. Join a community of fellow developers.
No spam. Unsubscribe at any time.