Now, what is dispatch of events???


Whenever you’re writing a svelte app, there might come a time when you need to send information from one component to another one, so that the another one can do something useful with it.
This is, in short, dispatch of events.

Using a component in another vs dispatching


Using one component in another component is quite straightforward in Svelte.
It just means - whatever is happening in the other component, make sure to happen in this one.
Like giving an example, when the code in Patrick.svelte looks like this & we are assuming that both the components are present in the same directory.

<script>
	function clickAlert() {
		alert('Hi! Mom');
	}
</script>

<button on:click={clickAlert}>
	Click Me
</button>

And our main App.svelte looks like:

<script>
	import Patrick from './Patrick.svelte'
</script>

<Patrick/>

Now, what if we need to do something more with the ‘Hi! Mom’ text in App.svelte
For that reason, dispatch of events are needed.
In order to do that, change the code in Patrick.svelte to this:

<script>
	import { createEventDispatcher } from 'svelte';

	const dispatch = createEventDispatcher();

	function sayHello() {
		dispatch('message', {
			text: 'Hello!'
		});
	}
</script>

<button on:click={sayHello}>
	Click to say hello
</button>

The entire information regarding createEventDispatcher can be found here. Anyway, the 'message' in dispatch() represents the name & the {text: 'Hello!'} represents detail.

Replace the App.svelte by this code:

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

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

<Inner on:message={handleMessage}/>

The on:message actually points to the name attribute in dispatch in Patrick.svelte. You can also change their values to see the change.


Now, what to do send a piece of information from some deep nested component to App.svelte. Luckily, Svelte has already done that for us❤️.
We just have to put an on:message event directive in all the intermediary components.
Like, <Inner on:message/> in Patrick.svelte where Patrick is the middle component and Inner is the deeply nested component.