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.

Create the custom event

In your stimulus controller, you can create a custom event using:

const event = new CustomEvent("update-map");
window.dispatchEvent(event);

Let’s break down this code.

  1. 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. Read more.
  2. 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.

data-action="update-map@window->map#updateHotspotLocation"

This will trigger the updateHotspotLocation method in map_controller.js.

And done!

You can now head over your receiving controller and continue coding.

Invite us to your inbox.

Articles, guides and interviews about web development and career progression.

Max 1-2x times per month.