Communicating between Stimulus controllers using custom events

Published in October 2019

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. You can read more about it here.
  2. Dispatch the event to the DOM and invoke the affected EventListeners (in our case, the data-action)

Link it to another controller using a data-action

In your HTML, define the following <mark>data-action</mark> 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.

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.

Full Stack Heroes logo

© 2020 Full Stack Heroes