Tally
Tally

Reputation: 11

Changing components via dispatching event to parent component

I have created a sandbox for this as it is more easily understood there.
https://codesandbox.io/s/svelte-playground-forked-dz7x8?file=/Page1.svelte

I am currently trying to change which component is displayed on the main page via passing the component through an Event Dispatcher.

    import Page2 from "./Page2.svelte"

    let dispatch = createEventDispatcher;
    function clickHandler(){
        dispatch("changeView", Page2)
    }
</script>
<main>
  <button on:click={clickHandler}>To Page 2</button>
  <h1> Page 1 </h1>
</main>

When this is dispatched it is handled by the parent component App.svelte to then change the component in
<svelte:component this={view} on:changeView={changeView} />

  let view = Page1
  const changeView = (e) => {
    view = e.detail;
  }
</script>
<main>

  <svelte:component this={view} on:changeView={changeView} />

</main>

But the error I am receiving:
Uncaught Error: Function called outside component initialization.

I feel like I am missing something obvious, any help on how to change between pages in a similar manner would be a great help.

Upvotes: 0

Views: 301

Answers (1)

Tally
Tally

Reputation: 11

As pointed out by @Golamrabbi-azad I missed some bloody parenthesis after createEventDispatcher in Page1 and 2....

let dispatch = createEventDispatcher; //should be
let dispatch = createEventDispatcher(); 

Thank you!

Upvotes: 1

Related Questions