Stimulus - Outlets API

Signal data changes across controller boundaries using the Stimulus Outlets API.

View Solution on Patreon
Stimulus - Outlets API

Premise

Inter-controller communication has been quite a drudgery in the past. Remember getControllerForElementAndIdentifier? This hasn’t been exactly a bliss to use. Being a private API, passing data directly from one controller to the other was even discouraged. This changed with the advent of the Outlets API, which we are going to take a look at.

Challenge

As an example, this time we are looking at a fictional background job dashboard. There’s a list of jobs with a status indicator on the left, and counter widgets on the right.

We are contemplating the scenario when data is provided as structured JSON, for example from a third party service. We simulate this by a sequence of JSON arrays in app.js, which are used to sequentially populate our jobs-dashboard-controller’s jobs value by use of an interval. This is meant to emulate the influx of real data.

This controller populates the job list the first time, should it be empty: https://stackblitz.com/edit/stimulus-outlets-api?file=app.js,index.html,controllers%2Fjob_dashboard_controller.js%3AL10,controllers%2Fjob_controller.js,controllers%2Fwidget_controller.js

Your challenge is to use the Outlets API to update each job’s indicator, as well as the widgets’ counters each time the incoming JSON changes:

https://stackblitz.com/edit/stimulus-outlets-api?file=app.js,index.html,controllers%2Fjob_dashboard_controller.js,controllers%2Fjob_controller.js%3AL8,controllers%2Fwidget_controller.js

https://stackblitz.com/edit/stimulus-outlets-api?file=app.js,index.html,controllers%2Fjob_dashboard_controller.js,controllers%2Fjob_controller.js,controllers%2Fwidget_controller.js%3AL8

Note that the respective outlet markup has already been added to the HTML!

Here’s a sneak peek at the result, have fun!

An example of a dashboard of async jobs being processed

More from

Stimulus - Orchestrate Complex UI Changes with Target Callbacks
07 May 2024

Use Stimulus target callbacks to dynamically update parts of your UI

Stimulus - Progressive Image Loading with Blurhash
23 April 2024

Improve Largest Contentful Paint using image blurhashes and Stimulus

Hotwire Combobox with Real Time Data
12 March 2024

Update combobox options using Websockets and Stimulus outlets

Cookies
essential