Skip to content

posva/event-emitter

Repository files navigation

EventEmitter ci npm package codecov thanks

Typed event and lightweight event emitter with a class based API

  • ⛓️ Typed: Powerful autocompletion and type checking
  • 📦 Class based: Add event emitting to your classes
  • 💨 Lightweight: 188 bytes min+brotli
  • 🌐 Runtime Agnostic: Works everywhere: Browser, node, Bun...

Installation

npm i @posva/event-emitter

Usage

import { EventEmitter } from '@posva/event-emitter'

const emitter = new EventEmitter<{
  // Define the events you want to emit and their arguments
  start: []
  // non tuples are also supported
  end: { reason: string }

  // You can also define multiple arguments
  sum: [number, number]
}>()

// no arguments
emitter.emit('start')
// object payload
emitter.emit('end', { reason: 'finished' })
// multiple arguments
emitter.emit('sum', 1, 2)

emitter.on('end', ({ reason }) => console.log('ended:', reason))

// You can also listen to all events

emitter.on('*', (event, payload) => {
  if (event === 'end') {
    // payload is always an array
    const [{ reason }] = payload
  } else if (event === 'sum') {
    const [a, b] = payload
  }
})

Since EventEmitter is a class, you can extend it in your own classes:

class CardGame extends EventEmitter<{
  start: []
  end: { winner: string }
  draw: [player: string, card: string]
  play: [player: string, card: string]
}> {
  start() {
    this.emit('start')
  }

  end(winner: string) {
    this.emit('end', { winner })
  }
}

API

Most of the code can be discovered through the autocompletion but the API documentation is available at https://event-emitter.esm.is.

Related

  • mitt: this library is a fork of mitt with a class based API and better types

License

MIT

About

<200 bytes type safe extendable event emitter / pubsub class

Resources

License

Code of conduct

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published