In this episode, we're connecting the dots between sorting a list in our UI and actually letting the rest of our app know what's happened. Basically, after we've dragged to rearrange our items, we want to communicate this new order up to our Alpine.js component, and eventually back to our Livewire component (or wherever your backend logic is).
We start by looking at the onSort
event from the Sortable library, which fires off every time we reorder the list. First, we log out some details to the console to see what Sortable gives us (pro-tip: it's got all the sorted IDs in there). Once we see those IDs, we cast them into an array and then, to make our lives easier later, make sure they're in integer format (not strings).
The key thing here is dispatching a custom event called sorted
using JavaScript's dispatchEvent
. We attach the sorted list as the event detail, and then over in our Alpine component, we listen for this event using x-on:sorted
. Once we catch it, we can easily use the event details (the new list order) to update whatever needs updating—like passing the sorted IDs back to Livewire.
So by the end of this one, we've got a nice loop: drag to sort, fire off an event with the new order, and be ready to sync that new order to the backend in the next episode. All the groundwork is set up and ready for back-end updates!