Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example eventlistener class for creating new event emitters.
class EventEmitter {
constructor() {
/* Events object for storing event symbols */
this._events = {};
}
/* Registers an event handler/listener in the Node.js style to be called once. */
once(eventName, handler) {
this.setupEventNameSpace(eventName);
this.registerEventHandler(eventName, "once", handler);
return this;
}
/* Registers an event handler/listener in the Node.js style to be called multiple times. */
on(eventName, handler) {
this.setupEventNameSpace(eventName);
this.registerEventHandler(eventName, "on", handler);
return this;
}
/* emit method for emitting events; if the symbol isn't available nothing happens.
* In any othercase, the functions listed under the event are executed.
*/
emit(eventName) {
let args = Array.prototype.slice.call(arguments);
if(this._events[eventName] !== undefined) {
this._events[eventName].forEach((listener, index) => {
if(/once/.test(listener.type)) {
console.log("Once Handler Removed");
this._events[eventName].splice(index, 1);
}
this.callHandler(listener.handler, args.slice(1));
});
}
}
/* Creates an array for each events listed functions/listeners.*/
setupEventNameSpace(eventName) {
if(this._events[eventName] === undefined) {
this._events[eventName] = [];
}
}
/* Registers event handlers by type */
registerEventHandler(eventName, type, handler) {
this._events[eventName].push({ type, handler });
}
/* Calls an event handler, passing any extra arguments given by the emit method */
callHandler(handler, args) {
if(typeof handler == 'function') {
handler.apply(this, args);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment