Type Safe Event Emitter
Simple event emitter for any Javascript runtime environment (browser, nodejs, etc...).
Uses Typescript's type inference feature to provide type safety for consumer and producer.
Table of contents
TL;DR
; ;ee.on`data`,;ee.emit`data`, `Important info`;
Installation
Command line
$ npm install --save inf-ee
CDN
https://unpkg.com/inf-ee@latest/dist/browser/event-emitter.min.js
Usage
Typescript
; ;ee.on`data`, ;ee.emit`data`, `Important info`;
NodeJS
const EventEmitter = EventEmitter; const e = ; e; e;
ES6 Modules
; const e = ; e; e;
Browser
Producer / Consumer example
producer.ts
- Producer constructs a type
EventSet
with a set of propertiesEventName
of typeEvent Handler
. - Producer exposes
on
,once
,off
methods for consumer in order to subscribe / unsubscribe to internal events. - Producer
emit
s events passing the supplied arguments to each handler.
// ----- producer.ts ; ;
consumer.ts
- Consumer subscribes to events.
- Consumer invokes object's methods and gets notified.
// ----- consumer.ts ; ; m.once'mathAction',;m.on'mathAction',;m.on'error', ; m.multiplication2.multiplication6.division3.division0;
output
I run only oncemultiplication: Old value is 1. New value is 2multiplication: Old value is 2. New value is 12division: Old value is 12. New value is 4Error! Can't divide by zero
API Reference
# on(eventName:
string | symbol | number, handler:
Function) : void
Adds the handler
to the end of the listeners array for the eventName
. No checks are made to see if the handler
has already been added. Multiple calls passing the same combination of eventName
and handler
will result in the listener being added, and called, multiple times.
# once(eventName:
string | symbol | number, handler:
Function) : void
Adds a one-time handler
function for the eventName
. The next time eventName
is triggered, this handler
is invoked and then removed.
# off(eventName:
string | symbol | number, handler:
Function) : void
Removes the specified handler
from the listener array for the eventName
. If the handler
has been added multiple times, then all references of that handler
will be removed.
# offByName(eventName:
string | symbol | number) : void
Removes all handlers, or those of the specified eventName
. It's bad practice. Use on own risk.
# offAll() : void
Removes all handlers of all events. It's bad practice. Use on own risk.
# has(eventName:
string | symbol | number, handler:
Function): boolean
Checks whether a handler
has been attached to eventName
# emit(eventName:
string | symbol | number, ...args:
Parameters<Function>): void
Synchronously calls each of the handlers registered for the eventName
, in the order they were registered, passing the supplied ...args
to each.
Tests
This module is well tested. You can run tests by executing the following command.
$ npm run test