Passing Parent Method to Child in Svelte

It's possible to pass methods down to child components, but it's a little awkward. A more idiomatic approach is to fire an event from the child component and listen for that event from the parent component:

App.html

<div>
  <TodoItem
    {todo}
    on:toggle="toggle(todo)"
  />
</div>
<script>
  import TodoItem from './TodoItem.html';
  export default {
    components: {
      TodoItem,
    },
    methods: {
      toggle(todo) {
        todo.done = !todo.done;
        const { todos } = this.get();
        this.set({ todos });
     }
   }
 };
</script>

TodoItem.html

<div>
  <button on:click="fire('toggle')">{todo.description}</button>
</div>

If you need to pass an event up through multiple levels of components you can just refire the event...

<TodoItem on:toggle="fire('toggle', event)">...</TodoItem>

...but there's a shorthand for doing so that means the same thing:

<TodoItem on:toggle>...</TodoItem>

Seems like "fire" was part of svelte v2 but in svelte v3 it's changed with createEventDispatcher

e.g -

child.svelte

<script>
    import { createEventDispatcher } from 'svelte';

    const dispatch = createEventDispatcher();

    function sayHello() {
        dispatch('message', {
            text: 'Hello!'
        });
    }
</script>

<button on:click={sayHello}>
    Click to say hello
</button>

parent.svelte

<script>
    import Inner from './child.svelte';

    function handleMessage(event) {
        alert(event.detail.text);
    }
</script>

<Inner on:message={handleMessage}/>

for more info - please visit : https://svelte.dev/tutorial/component-events

Tags:

Svelte