To listen for child dispatched events from any parent element, we know we can use the createEventDispatcher
function. However, that is not the focus of this post.
In some cases, we want to listen for a parent dispatched event from a child.
This can be achieved in a few ways, such as using props or methods drilling. By the way, I prefer to use a event-driven pattern.
This pattern offers several advantages compared to drilling:
-
It eliminates the maintenance difficulties associated with tracking props or methods through multiple layers.
-
It avoids creating a tight coupling between components.
Code example"undefined" anchor link
We can use the native Web API dispatchEvent
and addEventListener
.
Just dispatch a CustomEvent
in the parent component, or where you need.
<script> function handleClick() { const event = new CustomEvent('message', { detail: 'Hello!' }); document.dispatchEvent(event); }</script>
<button type="button" on:click={handleClick}> Parent dispatching an event </button>
Then, listen to that CustomEvent
in the child element using addEventListener
.
<script> document.addEventListener('message', (e) => { alert(`Message received: ${e.detail}`); });</script>
<p>Child listening to the event</p>
With this easy pattern, you can easily listen for child dispatched events from any parent element, ensuring that the project remains effortlessly scalable
I hope you found this article useful.
Happy coding! 🚀