Custom Event Listeners in Svelte

- 1 minute read

Consider the following Button.svelte component:

<!-- Button.svelte -->
<script>
    let i = 0;

    const increment = () => {
        i++;
        i % 10 === 0
            ? dispatch(`customEvent`, true);
            : dispatch(`customEvent`, false);
    };
</script>

<button on:click={increment} />

This component emits a custom event called customEvent each time the button is clicked.

On every tenth button click, the value true is dispatched, and on every other button click, the value false is dispatched.

Consider the following Widget.svelte component, which inherits the Button.svelte component:

<!-- Widget.svelte -->
<script>
    import Button from '$lib/components/Button.svelte';

    let isTenthClick = false;

    const customEventHandler = (e) => {
        isTenthClick = e.detail;
    };
</script>

<Button on:customEvent={customEventHandler} />

<p>Is tenth click: {isTenthClick}</p>

The above component attaches a handler called customEventListener to handle the customEvent event.

Notice how the boolean dispatched by Button.svelte is stored in e.detail, not e itself.

This is a simple example, but you can dispatch an arbitrary value of any type.

Link to this section Conclusion

You can also create and dispatch custom events in vanilla JavaScript, though it works a tad differently in Svelte.

Anyway, I hope this helped you!