Search code examples
event-handlingdom-eventssveltesvelte-3svelte-component

Pass event options to on:event directive


Is it possible to pass event options to a svelte on:* directive?

To register an event listener with options I currently use:

<script lang="ts">
  import { onMount } from "svelte"
  
  let root: HTMLElement

  onMount(() => {
    const touchHandlerOptions = {
      passive: true,
    }

    root.addEventListener("touchstart", handleTouchStart, touchHandlerOptions)
  })
</script>

<div bind:this={root} />

Wondering if this could be refactored to pass the options in an on:* directive directly?


Solution

  • There is no way to pass options directly, but you can use event-modifiers:

    <div on:touchstart|passive={handleTouchStart}>
    

    See docs