@kitbag/events
TypeScript icon, indicating that this package has built-in type declarations

0.1.1 • Public • Published

@kitbag/events

A simple lightweight event bus written in Typescript.

NPM Version GitHub Status Netlify Status Discord chat

Getting Started

Get started with the documentation

Installation

# bun
bun add @kitbag/events
# yarn
yarn add @kitbag/events
# npm
npm install @kitbag/events

Create an Emitter

import { createEmitter } from '@kitbag/events'

type Events = {
  hello: 'world'
}

export const emitter = createEmitter<Events>()

Add Listeners

emitter.on('hello', value => {
  console.log(value)
})

Emit Events

emitter.emit('hello', 'world')
// console logs "world"

Events

The Events type defines what events can be emitted and their payload.

type Events = {
  ping: 'pong',
  userCreated: User,
  eventWithNoPayload: void,
}

Usage

Broadcast Channel

By default Kitbag Events only emits events within the document. Alternatively, you can configure Events to use a Broadcast Channel which enables you to broadcast events across different windows, tabs, frames or iframes of the same origin.

import { createEmitter } from '@kitbag/events'

const emitter = createEmitter({
  broadcastChannel: 'MyChannelName'
})

Single Event Handler

Define a handler for a single event called "hello"

emitter.on('hello', value => {
  console.log(value) // "world"
})

Global Event Handler

Every event emitted will trigger this callback

emitter.on(event => {
  console.log(event) // { kind: 'hello', payload: 'world' }
})

Single Use Handler

Listen for a single event and then automatically remove the handler

emitter.once(...)

Removing listeners

Emitter.on returns the off method for removing an event handler

const off = emitter.on(...)

Manually remove an event handler

const handler = (value) => console.log(value)
const globalHandler = (event) => console.log(event)

emitter.on('hello', handler)
emitter.on(globalHandler)

emitter.off('hello', handler)
emitter.off(globalHandler)

Remove all handlers for a given event

const handler1 = (value) => console.log(value)
const handler2 = (value) => console.log(value)

emitter.on('hello', handler1)
emitter.on('hello', handler2)

emitter.off('hello')

Remove all handlers for all events

emitter.clear()

Readme

Keywords

none

Package Sidebar

Install

npm i @kitbag/events

Weekly Downloads

82

Version

0.1.1

License

none

Unpacked Size

9.45 kB

Total Files

6

Last publish

Collaborators

  • stackoverfloweth
  • charsh