Strict Events
Yet another EventEmitter
like, with a few gimmicks:
-
You define a finite set of emittable events, and you make it an Events class
-
An Events object derives two objects, Emitter and Listener, to separate concerns and do better typechecks
Extensive checks occur within process.env.NODE_ENV='development'
and are ignored within process.env.NODE_ENV='production'
.
let test; // define a finite events set.// values don't matter, they must only be unique.const EVENTS = A: 'a' B: 'b' C: 'c'; // alternatively you could write// const EVENTS = _.invert(['A', 'B', 'C']); // create a new Events class for this events setconst Events = ; // instanciate a new Events objectconst events = ;// extract a listener and an emitterconst listener emitter = events; // listener and emitter cannot be (mistakenly) overwrittentest = false;try eventslistener = null; catche test = true; testshouldbetrue; test = false;try eventsemitter = null; catche test = true; testshouldbetrue; // typecheck using instanceofeventsshouldbean;listenershouldbean;emittershouldbean; test = false;// bind a handlerlistener;testshouldbefalse;// synchronously trigger events with a params objectemitter;testshouldbetrue; let count = 0;// listener.on returns a referencelet ref = listener;emitter;countshouldbe;// this reference can be used with .off to remove a previously// attached handlerlistener;emitter;countshouldbe; test = false;try // this event is not in the predefined set: it will throw emitter;catche test = true;testshouldbetrue; // clear all handlers referencesevents;test = false;// this won't call the previously bind callbackevents;testshouldbefalse;