javascript / intermediate
Snippet
Simplifying Communication with Event Forwarding
Components can forward events to their parents without explicitly handling them. By adding on:eventname without a value, Svelte passes the event up the hierarchy, reducing boilerplate in nested component structures.
snippet.js
javascript
1
2
3
4
5
6
7
<!-- Parent.svelte --><Child on:message /><!-- Child.svelte --><button on:click={() => dispatch('message', 'Hello')}>Click me</button>
svelte
Breakdown
1
<Child on:message />
Short-hand for forwarding the 'message' event from Child to the grandparent component.
2
dispatch('message', 'Hello')
The original event emitted by the child component.