javascript - How to dispatch multiple events from a component? - Stack Overflow

admin2025-04-17  2

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?

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?

Share Improve this question edited Jan 31 at 8:47 brunnerh 186k30 gold badges357 silver badges430 bronze badges asked Jan 31 at 8:28 MannyManny 5661 gold badge9 silver badges23 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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

转载请注明原文地址:http://anycun.com/QandA/1744874643a88848.html