Skip to main content

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>

createEventDispatcher must be called when the component is first instantiated — you can't do it later inside e.g. a setTimeout callback. This links dispatch to 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', {...}) to dispatch('greet', {...}) in Inner.svelte and change the attribute name from on:message to on:greet in App.svelte.

Next: Event forwarding

<script>
import Inner from './Inner.svelte';

function handleMessage(event) {
alert(event.detail.text);
}
</script>

<Inner />


> tutorial@0.0.1 dev
> ./node_modules/vite/bin/vite.js dev


Forced re-optimization of dependencies

VITE v4.3.9 ready in 2782 ms

Local: http://localhost:5173/
Network: use --host to expose
press h to show help
6:33:38 PM [vite] Failed to load source map for /@vite/client.
6:33:38 PM [vite] Failed to load source map for /node_modules/vite/dist/client/env.mjs.