event-emitters
TypeScript icon, indicating that this package has built-in type declarations

1.0.6 • Public • Published

event-emitters

build status Known Vulnerabilities Renovate

Typesafe event emitters.

EventEmitter<T>

Similar to node's EventEmitter but:

  • Only emits a single event of type T.
  • Throw an exception when a client registers the same listener more than once.
  • Throw an exception when a client tries to remove a listener that is not listening.
  • Support async iteration.
const emitter = new EventEmitter<number>()
const listener = (n: number): void => {
  console.log(n)
}

emitter.subscribe(listener)
emitter.emit(42)

try {
  emitter.subscribe(listener)
} catch (e) {
  console.log('same listener')
}

emitter.unsubscribe(listener)
try {
  emitter.unsubscribe(() => {})
} catch (e) {
  console.log('listener not found')
}

The above will log:

42
same listener
listener not found
const emitter = new EventEmitter<number>()

async function logEmitterValues(emitter: EventEmitter<number>) {
  for await (const val of emitter) {
    console.log(val)
  }
}

logEmitterValues(emitter)

emitter.emit(42)
emitter.emit(43)

The above will log:

42
43
const emitter = new EventEmitter<number>()
const listener = emitter.subscribe((val: number) => {
  console.log(val)
})
emitter.unsubscribe(listener)

subscribe returns the callback passed to it which can be useful for unsubscribing later.

EventEmitterWithCurrent<T>

Provides the same API as EventEmitter but:

  • Is initialized with the current message.
  • Emits the current message to each listener as soon as it subscribes.
const emitter = new EventEmitterWithCurrent<number>(42)
emitter.subscribe((n: number): void => {
  console.log(n)
})
emitter.emit(43)

The above will log:

42
43

EventEmitterWithOptionalCurrent<T>

Provides the same API as EventEmitterWithCurrent but:

  • Can optionally be initialized with the current message.
  • Emits the current message to each listener as soon as it subscribes only when the current message is available.
const emitter = new EventEmitterWithCurrent<number>()
emitter.subscribe((n: number): void => {
  console.log(n)
})
emitter.emit(43)

The above will log:

43

QueueingEventEmitter<T>

Provides the same API as EventEmitter but:

  • Queues messages when there are no subscribers.
  • Delivers queued message to the first subscriber, then drains the queue.
const emitter = new EventEmitterWithCurrent<number>(42)
emitter.emit(44)
emitter.emit(45)
emitter.subscribe((n: number): void => {
  console.log(n)
})
emitter.emit(46)

The above will log:

44
45
46

Dependencies (0)

    Dev Dependencies (13)

    Package Sidebar

    Install

    npm i event-emitters

    Weekly Downloads

    70

    Version

    1.0.6

    License

    ISC

    Unpacked Size

    172 kB

    Total Files

    111

    Last publish

    Collaborators

    • jpike