Simple eventbus realization based on internal Svelte's tools only.
Use when you need handle events from deeply-nested child components without events forwarding.
-
You can set event listeners on
Eventbuscomponent and catch any event created withcreateEventbusDispatcherin any child component. -
Events are isolated inside of
Eventbuscomponent instance. You can have more than oneEventbusin the parent component. Each will listen events from it's child components only. -
If you have several nested
Eventbuscomponents, events will bubble through them while needed event listener will be occurred.
Parent - App.svelte
<script>
import {Eventbus} from 'svelte-eventbus';
import Child from './Child.svelte';
let totalclicks = 0;
</script>
<p>Total clicks: {totalclicks}</p>
<Eventbus on:button_click={()=>totalclicks++}>
<!-- There can be childs in any nest level-->
<Child />
</Eventbus>Nested - Child.svelte
<script>
import {createEventbusDispatcher} from 'svelte-eventbus';
const dispatch = createEventbusDispatcher();
</script>
<button on:click={()=>dispatch('button_click')}>Click</button>