| | |

Svelte 30 ๐Ÿงก Custom Event Handler Delegation via Props Callbacks

โฑ๏ธ Estimated read: 7 min | |

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

PatternSyntax
Requiredlet { cb } = $props()
Optionallet { cb } = $props<{ cb?: () => void }>()
Defaultlet { cb = () => {} } = $props()

Naming Conventions

PrefixUsage
onStandard 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

PitfallWhy It HappensFix
Null PointerCalling onSave() when undefinedUse onSave?.() or default
Callback HellToo many nested propsRefactor/Composition
Type MismatchMissing type annotationUse TS interfaces
Implicit EventsExpecting DOM bubblingSwitch 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

ItemValue
MechanismCallback delegation
Syntax$props()
Type SafetyHigh (TS Interfaces)
Legacy APIcreateEventDispatcher
Conventionon[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 chaining onSave?.() 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.

Was this helpful?


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!