Sending Events Up the Svelte Component Tree With createEventDispatcher

Jan 14, 2022

User avatar

Instructor

Scott Tolinski

Sometimes you're writing a component in Svelte and you would really like for an event to take place inside of the component but consume the results of the event in a parent. This is where Svelte's createEventDispatcher comes into play.

createEventDispatcher is part of Svelte core and is used like this.

Child

	import { createEventDispatcher } from 'svelte';

	const dispatch = createEventDispatcher();

	function sayHello() {
		dispatch('message', {
			text: 'Hello!'
		});
	}

This, then produces a Svelte style event on the usage of the component via the standard 'on' syntax. ie on:eventName. In this exampled pulled from the official Svelte tutorial, we're dispatching an event named 'message', so therefore the even will be on:message.

Parent

<Inner on:message={anyFunctionYouWant}/>

See the official Svelte Tutorial for a great interactive example on how to use. https://svelte.dev/tutorial/component-events