@jeppech/typed-emitter
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

Typed event emitter

This is a fairly simple class, for emitting/subscriping to typed events

Installation

Use your favourite package manager.

pnpm add @jeppech/typed-emitter

Usage

import { TypedEmitter } from '@jeppech/typed-emitter'

// Start by declaring an interface, describing your events and data types

interface EventData {
  id: number
  user: string
  message: string
}

interface MyEvents {
  'data': EventData
  'connected': undefined
  'disconnected': undefined
}

const emitter = TypedEmitter<MyEvents>()

// Note you get hints, when using the methods of the emitter.
emitter.on('data', (data) => {
  // data is EventData-type
})

emitter.emit('data', {
  'id': 1,
  'user': 'jeppech',
  'message': 'Hello!'
})

Extending class

class MyClass extends TypedEmitter<MyEvents> {
  constructor() {
    super()

    this.on('data', (data) => {
      // data is EventData-type
    })
  }
}

Package Sidebar

Install

npm i @jeppech/typed-emitter

Weekly Downloads

0

Version

1.1.0

License

ISC

Unpacked Size

3.72 kB

Total Files

4

Last publish

Collaborators

  • jeppech