最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论