$dispatch Magic Method
Fire custom DOM events for parent-child communication.
What is $dispatch?
$dispatch fires a custom browser event that bubbles up the DOM. It's the standard way in Alpine to communicate from a child component to a parent component, or even to plain JavaScript listeners.
When to Use
Use $dispatch whenever a child component needs to notify a parent about an action: a modal closing, an item added to cart, a form submission, or any custom event.
Basic Example
<!-- Child -->
<div x-data>
<button @click="$dispatch('notify', { message: 'Hello!' })">Notify</button>
</div>
<!-- Parent -->
<div x-data @notify="handle($event.detail.message)">
...
</div>Listening in Plain JS
You can also listen for these events outside of Alpine using standard JavaScript. This makes Alpine components easy to integrate with existing code.
window.addEventListener('notify', (e) => {
console.log(e.detail.message);
});💡 Tip
Always pass data as the second argument to $dispatch. The data will be available via $event.detail in the handler.
Can $dispatch pass data to a specific component?
No, events bubble up the DOM tree. To target a specific component, you'd typically use the event name to identify the action and let the parent decide how to handle it.