Part 1 / Events / Component events
Components can also dispatch events. To do so, they must create an event dispatcher. Update Inner.svelte:
Inner.svelte
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function sayHello() {
dispatch('message', {
text: 'Hello!'
});
}
</script>
createEventDispatchermust be called when the component is first instantiated — you can't do it later inside e.g. asetTimeoutcallback. This linksdispatchto the component instance.
Then, add an on:message handler in App.svelte:
App.svelte
<Inner on:message={handleMessage} />You can also try changing the event name to something else. For instance, change
dispatch('message')todispatch('greet')inInner.svelteand change the attribute name fromon:messagetoon:greetinApp.svelte.
1
2
3
4
5
6
7
8
9
10
<script>
import Inner from './Inner.svelte';
function handleMessage(event) {alert(event.detail.text);
}
</script>
<Inner />
initialising