Svelte 30 ๐งก Custom Event Handler Delegation via Props Callbacks
In legacy Svelte, custom events were handled by the createEventDispatcher function, an implicit mechanism that relied on event bubbling and a custom API to communicate from child components to parents. While effective, it suffered from “magic” behaviorโit was difficult to trace events through a component tree, and it lacked robust TypeScript support. Svelte 5 moves away from this implicit dispatching in favor of explicit callback props.
By passing functions as propsโoften called “callback delegation”โyou treat events like any other data. A child component declares a prop for an event handler, and the parent passes a function to it. This approach provides a clear, type-safe contract between components, making the data flow transparent and easy to debug. This chapter explores how to replace the legacy createEventDispatcher pattern with explicit callback delegation.
Key point: Callback delegation via props treats events as explicit function arguments; it makes component interfaces self-documenting and enables native TypeScript support, removing the need for implicit event-bubbling APIs.
Why Custom Event Handler Delegation exists
The clarity of explicit contracts. When an event is passed as a prop, the component’s interface declares exactly what the parent needs to provide. There is no guesswork about which events a component might emit; it is all defined in the $props() interface.
Native TypeScript support. Legacy dispatchers were notorious for being difficult to type. Callback props are standard JavaScript functions. You can easily define their signature (parameters and return types) using standard TypeScript interfaces.
Better trace-ability. With dispatchers, you had to follow a bubbling chain to find where an event was handled. With callbacks, you can use standard IDE “Go to Definition” features to navigate directly from the child componentโs invocation to the parentโs handler function.
Decoupling from event bubbling. Legacy events relied on DOM bubbling. If a developer stopped propagation (e.stopPropagation()) at the wrong place, the event would disappear. Callback props are not subject to the rules of the DOM treeโthey are direct function calls between the parent and child.
Avoidance of “magic” APIs. createEventDispatcher was a unique Svelte abstraction. By using standard function-as-prop patterns, you align Svelte code with common patterns found in React, Vue 3, and native JavaScript development.
a. The shift from createEventDispatcher
In the legacy model, a child component “fired” an event, and the parent “listened” to it. In the Svelte 5 model, the child “invokes” a callback that the parent provided. The child doesn’t need to know who is listening; it only needs to know that a function was provided to it.
<!-- Legacy -->
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
</script>
<button on:click={() => dispatch('save', data)}>Save</button>
<!-- Svelte 5 -->
<script>
let { onSave } = $props();
</script>
<button onclick={() => onSave(data)}>Save</button>
This makes the child component purely functional. It receives data in (props) and sends requests out (callbacks). It no longer carries the overhead of the Svelte dispatcher system.
b. Implementing callback props
Callback props are declared within the $props() rune, just like any other variable. By convention, event-related callbacks are prefixed with on (e.g., onSave, onClose, onUpdate).
<script>
// Declare the callback as a prop
let { onSave }: { onSave: (data: string) => void } = $props();
</script>
<button onclick={() => onSave("Success!")}>
Save Changes
</button>
When the parent uses this component, it passes a handler function. This creates an explicit link. If the parent doesn’t provide an onSave handler, you can either make it optional (by marking it as onSave?: ...) or use an empty arrow function as a fallback default: let { onSave = () => {} } = $props();.
c. Type-safe signatures
Because these are standard functions, you can define rich signatures. This allows the child to send specific data structures back to the parent, and the parent gets full autocompletion when writing the handler.
// Define the signature
type SaveHandler = (payload: { id: number, status: string }) => void;
// In the child component
let { onSave }: { onSave: SaveHandler } = $props();
This pattern is especially useful for complex UI components like auto-complete inputs or multi-step wizards. The type-safety ensures that if the child updates the payload format (e.g., adding an id), the parent component’s handler will immediately show a type error, forcing the developer to update the parentโs logic simultaneously.
Complete Example Session
// ============================================
// PART 1: CHILD COMPONENT
// ============================================
// Modal.svelte
let { onClose, onConfirm }: {
onClose: () => void,
onConfirm: (val: string) => void
} = $props();
<div class="modal">
<button onclick={onClose}>Cancel</button>
<button onclick={() => onConfirm("Confirmed")}>Confirm</button>
</div>
// ============================================
// PART 2: PARENT COMPONENT
// ============================================
// App.svelte
function handleConfirm(val: string) {
console.log("Action:", val);
}
<Modal
onClose={() => show = false}
onConfirm={handleConfirm}
/>
This sequence demonstrates the explicit contract: the parent provides the logic, and the child component executes it when the relevant interaction occurs.
Quick Reference
Callback Prop Patterns
| Pattern | Syntax |
|---|---|
| Required | let { cb } = $props() |
| Optional | let { cb } = $props<{ cb?: () => void }>() |
| Default | let { cb = () => {} } = $props() |
Naming Conventions
| Prefix | Usage |
|---|---|
on | Standard prefix for all callbacks |
on[Event] | e.g., onSave, onInput, onDelete |
Best Practices
โ Do This:
// Use the 'on' prefix for clarity
let { onUpdate } = $props(); // โ
// Provide fallback default to avoid undefined errors
let { onSave = () => {} } = $props(); // โ
// Define types for complex handlers
let { onData }: { onData: (d: Data) => void } = $props(); // โ
โ Don’t Do This:
// Don't use createEventDispatcher
import { createEventDispatcher } from 'svelte'; // โ
// Don't leave handlers undefined if not optional
let { onAction } = $props();
// Calling onAction() will crash if undefined // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Null Pointer | Calling onSave() when undefined | Use onSave?.() or default |
| Callback Hell | Too many nested props | Refactor/Composition |
| Type Mismatch | Missing type annotation | Use TS interfaces |
| Implicit Events | Expecting DOM bubbling | Switch to props |
Real-World Examples
1. Simple Close Button
let { onClose } = $props();
<button onclick={onClose}>Close</button>
2. Data Submission
let { onSave } = $props();
<button onclick={() => onSave(data)}>Save</button>
3. Selection Handler
let { onSelect } = $props();
<li onclick={() => onSelect(item.id)}>...</li>
4. Delete Confirm
let { onDelete } = $props();
<button onclick={onDelete}>Delete</button>
5. Wizard Navigation
let { onNext, onPrev } = $props();
6. Custom Input Change
let { onChange } = $props();
<input oninput={(e) => onChange(e.currentTarget.value)} />
7. Tab Switcher
let { onTabChange } = $props();
8. Drag Over Delegate
let { onDrop } = $props();
9. Error Handler Delegate
let { onError } = $props();
10. Toggle Callback
let { onToggle } = $props();
Visual
Event Dispatcher (Legacy) vs Callback Props (Modern)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LEGACY DISPATCHER โ
โ Child โโโโบ (Bubbling Event) โโโโบ Parentโ
โ (Hidden, Implicit, Untyped) โ
โ โ
โ CALLBACK PROPS โ
โ Child โโโโบ (Function Call) โโโโบ Parentโ
โ (Explicit, Visible, Typed) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Contractual Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ PARENT โ
โ function handle() { ... } โ
โ <Child onSave={handle} /> โ
โ โ โ
โ โผ (Passed Reference) โ
โ CHILD โ
โ onSave() // Executed โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Mechanism | Callback delegation |
| Syntax | $props() |
| Type Safety | High (TS Interfaces) |
| Legacy API | createEventDispatcher |
| Convention | on[Name] prefix |
Key takeaways:
- Prefer callbacks to dispatchers. Callback delegation via props is the new standard; it is more readable, maintainable, and type-safe than the legacy dispatcher system.
- Explicit contracts. Define your component’s needs in the
$props()declaration to create a clear API for users of your components. - Always provide a safety net. If a callback is optional, ensure you have a default
() => {}or use optional chainingonSave?.()when invoking it. - Standardize naming. Use the
on[Action]convention to clearly signal to other developers that the prop is an event callback. - Leverage TypeScript. Define function signatures for your callbacks to get full editor support for arguments and return types.
Remember: Callback delegation transforms your components into predictable, self-contained units. Instead of relying on hidden bubbling mechanics, you are building explicit relationships between parents and children. This shift makes your application significantly easier to read, navigate, and refactor as it scales.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!