Now I'm confused how to fire function from component to control something in another component. Can anyone help me on this?
Structure:
App.svelte
L checklist.svelte
L button <-- this button want to call function in stage component
L stage.svelte
checklist.svelte:
<button on:click="handleMove" />
stage.svelte:
export function fly(x, y) {
$map.flyto(x, y);
}
I have a button in checklist component that want to activate function that in stage component.
Stage component is a map that have x y position and function that move things inside this component.
How can I call function in stage component from the outside (checklist components)?
You have a couple of options:
first and the most flexible one is to create a writable store to use it anywhere
second it to use context
third is to declare it in App.svelte and bind it to both children
You could do the following:
checklist-click event from Checklist.fly on Stage.<!-- App.svelte -->
<script>
import Checklist from './Checklist.svelte';
import Stage from './Stage.svelte';
let stage;
function handleClick({ detail }) {
// these come from the second argument to dispatch in Checklist.svelte
const { x, y } = detail;
stage.fly(x, y);
}
</script>
<h1>App</h1>
<!-- Listen to the event fired with dispatch('checklist-click') -->
<Checklist on:checklist-click={handleClick}></Checklist>
<!-- Store a reference to this component instance so that we can call `fly` on it -->
<Stage bind:this={stage}></Stage>
<!-- Checklist.svelte -->
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function handleMove() {
dispatch('checklist-click', {x: 5, y: 10});
}
</script>
<h2>Checklist</h2>
<button on:click={handleMove}>
Move
</button>
<!-- Stage.svelte -->
<script>
export function fly(x, y) {
console.log(`fly called from stage with x: ${x}, y: ${y}`);
}
</script>
<h2>Stage</h2>
For more on dispatching component events, see the Svelte tutorial.