EventBus.js

/**
 * @class EventBus
 * @description event bus allows emitting of events and adding event
 * listeners
 * @param {Event} Event - an event class
 * @param {EventHolder} EventHolder - event holder class
 */
class EventBus {
    _events = null;

    constructor(Event, EventHolder) {
        const errors = [];
        if (typeof Event === 'undefined') {
            errors.push('Expected Event to be passed in');
        }
        if (typeof EventHolder === 'undefined') {
            errors.push('Expected EventHolder to be passed in');
        }
        if (errors.length > 0) {
            const error = new TypeError('Invalid EventBus Parameters');
            error.details = errors;
            throw error;
        }

        this._Event = Event;
        this._EventHolder = EventHolder;
        this._events = new this._EventHolder();
    }

    /**
     * @function addListener
     * @description adds an event listener to the bus
     * @memberof EventBus
     * @instance
     * @param {string} eventName - the name of the event
     * @param {Function} callback - the function to call on the event
     * @returns {Event} - the new event
     */
    addListener(eventName, callback) {
        const event = new this._Event(eventName, callback);
        this._events.add(event.eventPath, event);
        return event;
    }

    /**
     * @function removeListener
     * @description removes an event from the event listener
     * @memberof EventBus
     * @instance
     * @param {Event} event - event to remove
     */
    removeListener(event) {
        this._events.remove(event.eventPath, event);
    }

    /**
     * @function emit
     * @description emits an event of the bus
     * @memberof EventBus
     * @instance
     * @param {string} name - the name of the event being emitted
     * @param {*} vals - the values to call the callback with
     */
    emit(name, vals) {
        const path = name.split(':');
        this._events.getCallbacks(path).forEach((e) => e.callback(vals, e));
    }
}

module.exports = EventBus;