Event.js

/**
 * @class Event
 * @description An Event class which stores the event path, callback, creates an
 * id, and can hold a function to remove it from the event holder
 * @property {Array<string>} eventPath - array containing the event path
 * @property {string} eventName - the name of the event
 * @property {number} id - the unique id of this event
 * @property {Function} removeCallback - callback used to remove the event from
 * the event holder
 *
 * @param {string} eventName - the name of the event, if path seperated by ':'
 * @param {Function} callback - the function to call when the event is triggered
 */
class Event {
    _eventName = null;
    _callback = null;
    _id = null;
    _remove = null;

    constructor(eventName, callback) {
        const errors = [];

        // Simple validation
        // eventName must be a string
        if (typeof eventName !== 'string') {
            errors.push(`eventName must be a string got: ${typeof eventName}`);
        }
        // callback must be a function
        if (typeof callback !== 'function') {
            errors.push(`callback must be a function got: ${typeof callback}`);
        }
        // if there are errors throw an error and add the details to it
        if (errors.length > 0) {
            const error = new TypeError('Incorrent Event Parameters');
            error.details = errors;
            throw error;
        }

        this._eventName = eventName;
        this._callback = callback;
        this._id = Event.counter;
    }

    get eventPath() {
        return this._eventName.split(':');
    }

    get eventName() {
        return this._eventName;
    }

    get callback() {
        return this._callback;
    }

    get id() {
        return this._id;
    }

    get removeCallback() {
        return this._remove;
    }

    set removeCallback(cb) {
        this._remove = cb;
    }

    /**
     * @function remove
     * @description removes this event from the event holder
     * @memberof Event
     * @instance
     */
    remove() {
        this._remove(this);
    }

    /**
     * @function toString
     * @description returns a stringified version of this event
     * @memberof Event
     * @instance
     * @returns {string} - string representation of this event
     */
    toString() {
        return JSON.stringify({
            id: this._id,
            eventName: this._eventName,
            callback: this._callback.toString(),
        });
    }

    /**
     * @property {number} _counter - stores the current id
     * @memberof Event
     * @static
     * @private
     * @returns {number} - the current id;
     */
    static _counter = 0;

    /**
     * @property {number} counter - increments the counter and returns the value
     * @memberof Event
     * @static
     * @returns {number} - the current id
     */
    static get counter() {
        Event._counter += 1;
        return Event._counter;
    }
}

module.exports = Event;