javascript / beginner
Snippet
Dispatching Custom Events with Payload Patterns in Svelte
Svelte uses the Event Dispatcher pattern to communicate from child components to parent components. Calling `createEventDispatcher()` creates a dispatcher function that broadcasts named events along with structured JavaScript payload objects.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>import { createEventDispatcher } from 'svelte';const dispatch = createEventDispatcher();function emitItemSave() {const payload = { id: 101, timestamp: Date.now() };dispatch('itemSaved', payload);}</script><button on:click={emitItemSave}>Save Record</button>
svelte
Breakdown
1
import { createEventDispatcher } from 'svelte';
Imports the helper factory function from the Svelte core library to enable custom component events.
2
const dispatch = createEventDispatcher();
Instantiates an event dispatcher function specific to the current component instance.
3
const payload = { id: 101, timestamp: Date.now() };
Constructs a JavaScript data object containing relevant details to send to listener components.
4
dispatch('itemSaved', payload);
Triggers the 'itemSaved' custom event and attaches the payload object to the event detail property.
5
<button on:click={emitItemSave}>
Wires the button click event to execute the event emitter function.