Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call svelte:component current component method?

Tags:

svelte

I have this basic app, with some components that have a public load method. On some actions, I'd like to call that method on the current svelte:component, but I have no idea how to get a reference to the component instance. How can one do that?

    <script>
        import router from 'page'
        import Wines from './pages/Wines.svelte'
        import Entry from './pages/Entry.svelte'
        import TitleBar from './components/TitleBar.svelte'

        let page,
            params

        router('/', () => page = Wines)
        router('/wines', () => page = Wines)
        router('/entry/:id?', (ctx, next) => {
            params = ctx.params
            next()
        }, () => page = Entry)

        async function forceSync(){
            // how to call current component instance?
        }

    </script>

    <main>
        <TitleBar on:sync-request={forceSync}></TitleBar>
        <svelte:component this={page} params={params}/>
    </main>
like image 960
Antoine Avatar asked Sep 17 '25 02:09

Antoine


1 Answers

You can use bind:this to get a reference to the current component and assign it to a variable. This also works for components rendered with <svelte:component> so you would organize you code similar to:

<script>
  import Child from './Child.svelte'

  let cmp

  const func = () => {
    // use cmp here: cmp.load()
  }
</script>

<svelte:component this="{Child}" bind:this="{cmp}" />
like image 65
Stephane Vanraes Avatar answered Sep 19 '25 21:09

Stephane Vanraes