@amelix/phoenix.js
Version:
A feature-rich API wrapper for the critically acclaimed chatting app Phoenix.. or something.
39 lines (38 loc) • 1.09 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
class EventEmitter {
constructor() {
this.callbacks = {};
this.onces = {};
}
/**
* Choose what happens on a particular event broadcasted by this event emitter.
*/
on(event, callback, once = false) {
if (!this.callbacks[event])
this.callbacks[event] = [];
this.callbacks[event].push(callback);
if (once)
this.onces[event] = 0;
}
/**
* Same as on(), except will only run the first time the event is emitted.
*/
once(event, callback) {
this.on(event, callback, true);
}
emit(event, ...args) {
if (this.onces[event] === 1)
return;
let callbacks = this.callbacks[event];
if (callbacks) {
for (let callback of callbacks) {
callback(...args);
}
}
if (this.onces[event] === 0) {
this.onces[event] = 1;
}
}
}
exports.default = EventEmitter;