Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a custom event in Svelte?

Tags:

svelte

I've been using on:click and looking for an event using Svelte. How do I trigger a custom event within a child component that I can capture in a parent component? I've seen a tutorial where I can pass in something like this, however, I couldn't get it to hook up.

<Component on:customClick={myThing}>

The child component has some logic that looks like this:

    <script>    
       export let myThing = '';
    <script>  

<input type="text" onClick={() => myThing= 'Update'} />

This does not seem to work, what am I missing?

like image 642
Jon Jones Avatar asked Sep 03 '25 03:09

Jon Jones


2 Answers

You could dispatch event from children component and handle it in parent component

// children component
<script>
    import { createEventDispatcher } from "svelte";

    const dispatch = createEventDispatcher();

    let count = 0;

    function handleClick() {
      count += 1;
      dispatch("customClick", {
        count
      });
    }
</script>

<button on:click={handleClick}>
  Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
// parent component
<script>
  import ChildrenComponent from "./ChildrenComponent.svelte";

  let count;

  const handleCustomClick = event => {
    count = event.detail.count;
  };
</script>

<main>
    <p>Parent count: {count || 0}</p>
    <ChildrenComponent on:customClick={handleCustomClick}/>
</main>

Below is the codesandbox demo

Edit restless-paper-n8ter

Reference:

Tutorials: Component events

like image 78
hgb123 Avatar answered Sep 06 '25 01:09

hgb123


Or like this (without dispatch):

Parent:

<script>
  import Child from "./Child.svelte";

  let count = 0;
  const handleClick = () => {
    count += 1;
  };
</script>

<main>
    <p>Parent count: {count}</p>
    <Child {count} on:click={handleClick} />
</main>

Child:

// child component
<script>
    export let count;
</script>

<button on:click>
  Clicked {count}
</button>
like image 41
voscausa Avatar answered Sep 06 '25 01:09

voscausa