Svelte Eventbus screenshot

Svelte Eventbus

Author Avatar Theme by Alexxnb
Updated: 18 Feb 2022
38 Stars

Simple eventbus realization based on internal Svelte's tools only

Overview:

The svelte-eventbus is a simple eventbus realization that is based on internal Svelte tools only. This eventbus allows developers to handle events from deeply-nested child components without the need for events forwarding.

Features:

  • Event Listeners: The eventbus component allows developers to set event listeners and catch any event created with the createEventbusDispatcher in any child component.
  • Isolated Events: Events are isolated within the Eventbus component instance, allowing for multiple Eventbus instances within a parent component. Each Eventbus will only listen to events from its child components.
  • Event Bubbling: If there are several nested Eventbus components, events will bubble through them until they reach the appropriate event listener.

Installation:

To install the svelte-eventbus theme, you can follow these steps:

  1. Add the package to your project using npm or yarn:
npm install svelte-eventbus

or

yarn add svelte-eventbus
  1. Import the necessary components into your Svelte files:
import { Eventbus, createEventbusDispatcher } from 'svelte-eventbus';
  1. Set event listeners on the Eventbus component and use the createEventbusDispatcher to create events in your child components. For example:
// Parent component - App.svelte
<script>
  import { Eventbus } from 'svelte-eventbus';
</script>

<div>
  <!-- Eventbus component -->
  <Eventbus />

  <!-- Child component -->
  <Child />
</div>

// Child component - Child.svelte
<script>
  import { createEventbusDispatcher } from 'svelte-eventbus';

  const dispatch = createEventbusDispatcher();
</script>

<div>
  <button on:click={() => dispatch('event:example')}>
    Click me
  </button>
</div>

Summary:

The svelte-eventbus is a simple and efficient eventbus tool for Svelte developers. It allows for easy event handling from deeply-nested child components without the need for events forwarding. With its ability to isolate events within specific Eventbus instances, developers have flexibility in managing events within their app. The eventbus also supports event bubbling, ensuring that events reach the appropriate event listeners.