I was wondering how to forward an event from a function with Svelte.
For example, I have an App.svelte and a Component.svelte files. Component.svelte is a button component. I want to handle the on:click event like so :
<script>
function handle(e){ /** Do things */ - /** Forward Event */ }
</script>
<button on:click={handle}/>
So I can also get the event from the App.svelte file
<script>
import Button from './component.svelte'
function handle(e){ /** Do something */ }
</script>
<div>
<Button on:click={handle}/>
</div>
I know you can forward events inside the component.svelte file by just filling an on:click attribute without specifying the function to call. But for my case, I need to have some internal logic going on inside my component. Or do I really need to create custom event handler for that ?
Thank you for your help :)
No, you don't need a custom event if the click is all you want to listen to but you want to perform logic inside the component and pass the click on to the parent.
Svelte allows you to add as many on:click's as you want. So one of the on:clicks can be empty and pass on the click handler to the parent and the other can handle the internal function/logic for the component.
Here's a REPL showing that it works, I usually use this to avoid the boilerplate of createEventDispatcher when all I need to know about is the click in both components. Of course, if you need the click to do something in the child and then some other stuff happens then the parent gets notified then you'll need to dispatch the event, but this works for your example.