You can install from NPM by doing:
npm install --save nomatic-events
var events = require("nomatic-events");
var EventEmitter = events.EventEmitter;
var emitter = new EventEmitter();
// Supports RegExp for listeners
var listener = emitter.on(/incoming/i, function(data) {
console.log("data is now " + data);
});
// `listener` is an EventListener, but you do not have to capture this.
emitter.emit("INCOMING", 42);
class EventedObject extends EventEmitter {
constructor() {
// Call EventEmitter, set maxListeners to 20
super(20);
this.listenerExecuted = true;
}
handleIncoming(some, option, or, another) {
// Variadic arguments supported
this.emit("INCOMING", some, option, or, another);
}
}
let evented = new EventedObject();
// Don't have to take every argument supplied by `emit`
evented.on(/IN/, function(some, option, or) {
console.log(this);
if (this.listeners) {
console.log(some, option, or);
this.listenerExecuted = true;
} else {
console.log("Bad context");
}
});
evented.handleIncoming("See no evil", "Hear no evil", "Speak no evil", 42);
// "See no evil"
// "Hear no evil"
// "Speak no evil"
You can also use AsyncEventEmitter
and AsyncEventListener
to handle Promise-based callbacks.
var events = require("nomatic-events");
var AsyncEventEmitter = events.AsyncEventEmitter;
var emitter = new AsyncEventEmitter();
var fs = require('fs');
var files = null;
var listener = emitter.on(/incoming/i, function(data) {
return new Promise((resolve, reject) => {
fs.readdir(__dirname, (err, list) => {
if (err) reject(err);
files = list;
resolve();
});
})
});
// `listener` is an AsyncEventListener, but you do not have to capture this.
// Executed asynchronously
emitter.emit("INCOMING", 42).then(() => {
// 'files' isn't null!
console.log(files);
});
// 'files' will still be null until promise resolves
Pride is taken when developing tests, you can find unit tests for both EventEmitter and EventListener here.
This package is written in TypeScript and declaration files are added to the NPM package. However, you do not even need to know what TypeScript is in order to use this package, let alone install the compiler. NPM packages include the compiled project.