I want to run two functions: one on:blur inside a component, and one on the component from the outside.
// CustomInput.svelte
<input on:blur={() => console.log(1)} />
// App.svelte
import CustomInput from "./CustomInput.svelte";
<CustomInput on:blur={() => console.log(2)} />
When the blur event is triggered 1
is logged in the console. Is there a way to run both callbacks and get 1
and 2
logged in the console?
Faniel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
The best solution I can think of:
// CustomInput.svelte
<script>
import { createEventDispatcher } from "svelte";
function handleBlur(event) {
console.log(1);
dispatch("blur", { event });
}
</script>
<input on:blur={handleBlur} />
// App.svelte
import CustomInput from "./CustomInput.svelte";
<CustomInput on:blur={() => console.log(2)} />
It would also be possible to send a function as a prop, then run it in handleBlur
. The reason I choose to dispatch blur is because I think it increases code readability.
Faniel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
You can forward the event in addition to handling it:
<input on:blur={() => console.log(1)} on:blur />