Source

event/AdmEventEmitter.js

"use strict"

/**
 *	----------------------------------------------------------------------------------------------
 *	Class AdmEventEmitter - Handling app events 
 * 	----------------------------------------------------------------------------------------------
 */
class AdmEventEmitter {

    /**
     * Create a EventEmitter instance.
     */
	constructor() {
		this._events = {};
	}

    /**
     * Add an event listener.
     * @param {string} name - Event name
	 * @param {Function} listener - Event handler	 
	 * @return {object} The emitter instance
     */
	addListener(name, listener) {
		if (!this._events[name]) {
			this._events[name] = [];
		}
		this._events[name].push(listener);
		return this;
	}

    /**
     * Remove a route.
     * @param {string} name - Event name
	 * @param {Function} listener - Event handler	 
	 * @return {object} The emitter instance
     */
	removeListener(name, listener) {
		if (!this._events[name]) {
			throw new Error(`EventEmitter:removeListener - Can't remove a listener. Event "${name}" doesn't exits.`);
		}
		const filterListeners = (item) => item !== listener;
		this._events[name] = this._events[name].filter(filterListeners);
	}

    /**
     * emit a route.
     * @param {string} name - Event name
	 * @param {anonym} data - Event data	 
     */
	emit(name, data) {
		if (!this._events[name]) {
			throw new Error(`EventEmitter:emit - Can't emit an event. Event "${name}" doesn't exits.`);
		}
		const fireCallbacks = (callback) => {
			callback(data);
		};
		this._events[name].forEach(fireCallbacks);
	}
}

export { AdmEventEmitter };