How to communicate between two AlpineJS components? How to trigger something on one component and show results on another?
Here is how!
The problem
We want to trigger an event in one component and show the result in another one. For example:
- show pop-up, regardless from which component is triggered
- expand another component
- any other communication between components
,
The Solution
Yes, as may be guessing - the solution is JavaScript events!
But how to trigger and listen JavaSript event in AlpineJS?
I can show you two different ways, one is using custom JS code and another one is by using built-in AlpinJS trigger=>listener methods
JavaScript events in AlpineJS
So, let's say we want to click on a button in one component and show an element in another one.
/*component 1 - dispatch event on click*/
<div
x-data="{
showHiddenElement(){
var custom_event = new CustomEvent('expand_upload_field', {
show: true,
detail: {
message:'open upload field'
}
});
window.dispatchEvent(custom_event);
}
}"
>
<u x-on:click="showHiddenElement()" class="cursor-pointer">
Click Me
</u>
</div>
/*component 2 - listen event*/
<div
x-data={showEl:false}
x-init="
window.addEventListener('expand_upload_field', event => {
message = event.detail.message;
//console.log(message);
showEl = true;
});
"
>
<div x-show="showEl">
Show this content
</div>
</div>
Component 1 will dispatch the event when user clicks on "Click me" text, and component 2 will show hidden element containing text "Show this element".
This example, has covered native JavaScript usage in Alpine JS, and in next example we will use AlpineJS built-in event/listener feature.
AlpineJS event listeners between components
/*component 1 - dispatch event on click*/
<div
>
<u @click="$dispatch('showelement',{message:'myValue'})" class="cursor-pointer">
Click Me
</u>
</div>
/*component 2 - listen event*/
<div
x-data={showEl:false} @showelement.window="(event)=>{showEl = true;console.log(event.detail.message)}">
<div x-show="showEl">
Show this content
</div>
</div>