Premise
The Hotwire mantra is to precalculate HTML on the server and send it over to the client in fully assembled form - a āwhite gloveā service, so to speak. Many developers Iāve met go to great lengths to even orchestrate every smallest UI change with tiny Turbo Stream fragments in pursuit of a āno JSā app.
š¶ļø However, sometimes all the information you need to update your UI is already there in the DOM. In such cases, using server-side rendered HTML changes feels like breaking a fly on a wheel. Not only will it consume precious CPU time on your servers, it also requires you to preserve and manage state somehow. In many cases like the present one, when those UI changes are only ephemeral, this is clearly overshooting the target.
Starting Point
In Challenge 18, we used Stimulusā Outlets API to solve a similar problem. We are going to take a bit of a different take on this: As jobs come in via Websockets, we want to use simple client-size logic to count and categorize them.
The setup goes like this:
- On the server, we emulate jobs being appended and removed to the
job-list
<ul>
via Websockets, similar to whatbroadcast_append_to
does:
https://stackblitz.com/edit/hotwire-club-stimulus-target-callbacks?file=index.js%3AL69
https://stackblitz.com/edit/hotwire-club-stimulus-target-callbacks?file=index.html%3AL48
The appended <li>
elements are itemTargets
of the global Stimulus job-list-controller
.
index.html
contains 4 statistics areas for the total count, and counts for the respective job types, each of them is its own Stimulus target:
https://stackblitz.com/edit/hotwire-club-stimulus-target-callbacks?file=index.html%3AL60
Challenge
Using Target Callbacks, update the counts in the statistics sidebar:
Hereās a preview of the end result:
Teaser
We are using custom data-job-type
attributes to discern the respective count targets. How could we make that more idiomatic Stimulus?