Svelte: Events Cheat Sheet

You can bind functions/ events to your tags:

<script>
  let count = 0;
  function handleClick() {
    count += 1;
  }
</script>
<button on:click={handleClick}>
  Clicked {count} {count === 1 ? 'time' : 'times'}
</button>

You can use all javascript event (click, mousemove, …). You can also modify event by piping modifiers to it: <button on:click|once={handleClick}> You can chain them by adding pipes.

Event dispatcher

You can create an event dispatcher inside a component. It must be called when the component is first instantiated.

<script>
  import { createEventDispatcher } from 'svelte';
  const dispatch = createEventDispatcher();
  function sayHello() {
    dispatch('message', {
      text: 'Hello!'
    });
  }
</script>

On the other side:

<script>
  import Inner from './Inner.svelte';
  function handleMessage(event) {
    alert(event.detail.text);
  }
</script>
<Inner on:message={handleMessage}/> // on:eventname

Event forwarding

You can handle events from any other component by calling them with their own event:

// Outer.svelte
<script>
  import Inner from './Inner.svelte';
</script>
<Inner on:message/>

Here we can intercept the event message from Inner. Then, when called, we can define how the component reacts:

<Outer on:message={handleMessage}/>