Discover how to make your components talk to each other effortlessly with event forwarding!
Why Event forwarding in Svelte? - Purpose & Use Cases
Imagine you have a button inside a custom component, and you want to know when it is clicked from the outside. You try to listen for the click event on the custom component itself.
Without event forwarding, the click event stays inside the button and does not reach the parent component. You end up writing extra code to manually catch and re-emit events, which is repetitive and error-prone.
Event forwarding lets the custom component automatically pass events from its inner elements to the outside. This means you can listen to events on the custom component directly, making your code cleaner and easier to manage.
function handleClick() { console.log('clicked'); }
<CustomButton on:click={handleClick} />
// But click does not trigger handleClick<CustomButton on:click={handleClick} />
// click event is forwarded and handleClick runsIt enables seamless communication from nested elements to parent components without extra boilerplate code.
Think of a music player with a custom play button component. You want to know when the user clicks play to start the music. Event forwarding lets you listen to the play button click directly on the player component.
Manual event handling inside components is tedious and error-prone.
Event forwarding automatically passes events outward for easy listening.
This leads to cleaner, simpler component communication.