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

Faceted Search with Stimulus and Turbo Frames
10 December 2024

Harness the power of Stimulus and Turbo Frames to drive a simple but powerful faceted search solution

Stimulus - Video Progress Tracker with LocalStorage
29 October 2024

Store ephemeral user state like video playback progress in localStorage

Stimulus - Image Upload Previews with `URL.createObjectURL`
17 September 2024

Create client-side previews of files using URL.createObjectURL

Cookies
essential