How to Use createEventDispatcher in Svelte for Component Events
In Svelte, use
createEventDispatcher to create a function that sends custom events from a child component to its parent. Call the dispatcher function with an event name and optional data to notify the parent component.Syntax
Use createEventDispatcher from svelte to get a dispatcher function. Call this function with an event name and optional detail data to send events.
import { createEventDispatcher } from 'svelte';— imports the dispatcher creator.const dispatch = createEventDispatcher();— creates the dispatcher function.dispatch('eventName', detailObject);— sends the event with optional data.
svelte
import { createEventDispatcher } from 'svelte'; const dispatch = createEventDispatcher(); // Use inside component functions or event handlers // dispatch('eventName', { key: 'value' });
Example
This example shows a child button component sending a message event with text data to its parent. The parent listens and displays the message.
svelte
<!-- Child.svelte --> <script> import { createEventDispatcher } from 'svelte'; const dispatch = createEventDispatcher(); function sendMessage() { dispatch('message', { text: 'Hello from child!' }); } </script> <button on:click={sendMessage}>Send Message</button> <!-- Parent.svelte --> <script> import Child from './Child.svelte'; let received = ''; function handleMessage(event) { received = event.detail.text; } </script> <Child on:message={handleMessage} /> <p>Received: {received}</p>
Output
A button labeled 'Send Message'. When clicked, the text 'Received: Hello from child!' appears below.
Common Pitfalls
Common mistakes include:
- Not importing
createEventDispatcherbefore using it. - Calling
dispatchoutside component script or before initialization. - Forgetting to listen for the event in the parent with
on:eventName. - Expecting the event detail directly on the event object instead of
event.detail.
svelte
/* Wrong: dispatch called without import or before creation */ // dispatch('message'); // Error: dispatch not defined /* Correct usage */ import { createEventDispatcher } from 'svelte'; const dispatch = createEventDispatcher(); // dispatch('message'); // Call inside functions or event handlers
Quick Reference
| Term | Description |
|---|---|
| createEventDispatcher() | Function to create a dispatcher for sending events |
| dispatch(eventName, detail?) | Function to send an event with optional data |
| on:eventName | Parent listens to the event from child component |
| event.detail | Access event data sent by dispatch |
Key Takeaways
Use createEventDispatcher inside a Svelte component to send custom events.
Call the dispatcher function with an event name and optional data object.
Listen to the event in the parent using on:eventName syntax.
Access event data in the parent via event.detail.
Always import createEventDispatcher from 'svelte' before using it.