How to Dispatch Custom Event in Svelte: Simple Guide
In Svelte, use
createEventDispatcher to dispatch custom events from a component. Call the dispatcher function with the event name and optional data to send events to parent components.Syntax
Use createEventDispatcher from svelte to create a dispatcher function. Call this function with the event name as a string and an optional payload object.
createEventDispatcher(): Initializes the dispatcher.dispatch('eventName', detail): Sends the event with optional data.
svelte
import { createEventDispatcher } from 'svelte'; const dispatch = createEventDispatcher(); dispatch('eventName', { key: 'value' });
Example
This example shows a child component dispatching a message event with data. The parent listens and reacts by displaying 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
Button labeled 'Send Message' visible. When clicked, text below updates to 'Received: Hello from child!'
Common Pitfalls
Common mistakes include:
- Not importing
createEventDispatcherbefore use. - Calling the dispatcher outside component setup or before initialization.
- Forgetting to listen for the custom event in the parent component.
- Using incorrect event names or mismatched casing.
Always ensure the parent uses on:eventName to listen.
svelte
/* Wrong: dispatch called without createEventDispatcher */ // const dispatch = () => {}; // dispatch('myEvent'); /* Right: */ import { createEventDispatcher } from 'svelte'; const dispatch = createEventDispatcher(); dispatch('myEvent');
Quick Reference
Remember these key points when dispatching custom events in Svelte:
- Import
createEventDispatcherfromsvelte. - Initialize dispatcher inside component script.
- Call dispatcher with event name and optional data.
- Listen to events in parent with
on:eventName.
Key Takeaways
Use createEventDispatcher() to create a dispatcher function inside your Svelte component.
Call the dispatcher with the event name and optional data to send custom events.
Listen for custom events in the parent component using on:eventName syntax.
Always import createEventDispatcher from 'svelte' before using it.
Ensure event names match exactly between dispatch and listener.