javascriptsveltesvelte-5

How to dispatch multiple events from a component?


Let's imagine we have simple <input> with onChange and onPaste event. In Svelte4 I have used to use this code:

import {createEventDispatcher} from "svelte";
const dispatch = createEventDispatcher();

function change() {
  dispatch("change");
}

function paste() {
  dispatch("paste");
  dispatch("change");
}
<input on:paste={paste} on:change={change} />

But in Svelte5 I should use (as it's written in the documentation) $props but I don't know how to dispatch multiple events (paste and change). Any ideas?


Solution

  • You essentially just call the props in sequence, e.g.

    let { onchange, onpaste } = $props();
    
    function paste() {
      onpaste?.();
      onchange?.();
    }
    
    <input {onchange} onpaste={paste} />
    

    If you want to make sure that each function is called, even if one handler throws an error, you will have to use additional try/catch wrappers.

    There is a slight inconsistency in the above example in that the onchange directly passed to the input will receive the event object and the one called within paste will not, though in the context of paste you only would have access to the paste event.

    You could of course pass that on, then component consumers should be informed that onchange can receive objects from both the paste and change event.

    function paste(e) {
      onpaste?.(e);
      onchange?.(e);
    }
    

    Playground