0 day streak
javascript / beginner
Snippet

Dispatching Component Events

To communicate from a child component back to a parent, Svelte uses an event dispatcher. The parent can then listen for these custom events using the 'on:' directive.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function notifyParent() {
dispatch('message', { text: 'Hello from Child!' });
}
</script>
<button on:click={notifyParent}>
Notify Parent
</button>
svelte
Breakdown
1
const dispatch = createEventDispatcher();
Initializes the dispatcher function for the current component.
2
dispatch('message', { ... });
Sends a custom event named 'message' with an optional data payload.