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

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

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 badges358 silver badges431 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745275024a4619987.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信