Svelte - Forwarding event from component scripting

1.5k views Asked by At

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 :)

3

There are 3 answers

0
JHeth On BEST ANSWER

Or do I really need to create custom event handler for that ?

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.

<button on:click={internalFunction} on:click>Something</button>

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.

1
grohjy On

I’m not sure if I understood correctly. You can handle your custom logic in your function and then just dispatch click forward.

In your component:

<script>
  import { createEventDispatcher } from 'svelte'
  const dispatch = createEventDispatcher()
  function handle(e){
    console.log(”comp”)
    dispatch('click', e)
  }
</script>
<button on:click={handle}>test</button>
2
Stephane Vanraes On

What you are looking for is the createEventDispatcher it allows you to 'manually' fire events. So what you would do is:

import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();

function handle(e) {
 // do stuff
 dispatch('my-event', data);
}

Now you can listen to this event using on:my-event (note that this can very well be on:click, or whatever), the data passed into this event can be accessed as ev.detail