sooon
sooon

Reputation: 4888

svelte - call function from specific component in a series of nested components

I have a nested component, that I will instance multiple copies in the app:

//App.svelte
<Nested /> // Nested-1 
<Nested /> // Nested-2
<Nested /> // Nested-3

in Nested I have export a function:

//Nested.svelte
export function doExample(){...}

What is the best way for me to call doExample() in Nested-2? One way i can think of is using id at the Nested:

//App.svelte
<Nested id="nested_1" /> // Nested-1 
<Nested id="nested_2" /> // Nested-2
<Nested id="nested_3" /> // Nested-3

then use getElementById() to identify the specific component then call the function. But is there a better way to achieve this?

Upvotes: 1

Views: 1000

Answers (1)

Stephane Vanraes
Stephane Vanraes

Reputation: 16451

You would do this by using bind on the instance and then call the function on that instance

<script>
  import Nested from './Nested.svelte'
  let child
  
  const action = () => child.doExample()
</script>

<Nested bind:this={child} />

Note that this would also work with an array:

<script>
  import Nested from './Nested.svelte'
  let children = []
  
  const action = i => children[i].doExample()
</script>

{#each array as item, i}
  <Nested bind:this={children[i]} />
{/each}

Upvotes: 1

Related Questions