Last active
July 29, 2018 08:52
-
-
Save davehax/85815d6ad894d728ba70ebe8f8900df4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Minimal Pub/Sub class | |
* | |
* @class EventEngine | |
*/ | |
class EventEngine { | |
/** | |
* Creates an instance of EventEngine. | |
* @memberof EventEngine | |
*/ | |
constructor() { | |
this.eventHandler = {}; | |
} | |
/** | |
* Attach an event handler to an event name | |
* | |
* @param {*} eventName | |
* @param {*} handler | |
* @returns | |
* @memberof EventEngine | |
*/ | |
on(eventName, handler) { | |
if (!eventName || !handler) { return; } | |
if (!this.eventHandler[eventName]) { this.eventHandler[eventName] = []; } | |
this.eventHandler[eventName].push(handler); | |
} | |
/** | |
* Removes a single event handler if specified, | |
* otherwise removes all event handlers for a given event | |
* | |
* @param {*} eventName | |
* @param {*} handler | |
* @returns | |
* @memberof EventEngine | |
*/ | |
off(eventName, handler) { | |
if (!eventName || !this.eventHandler[eventName]) { return; } | |
if (typeof (handler) === "function") { | |
// Remove a single event handler for {eventName} | |
var idx = this.eventHandler[eventName].indexOf(handler); | |
if (idx > -1) { | |
this.eventHandler[eventName].splice(idx, 1); | |
} | |
} | |
else { | |
// Remove all event handlers for {eventName} | |
this.eventHandler[eventName] = []; | |
} | |
} | |
/** | |
* Trigger an event. Optionally pass argument(s) and/or scope | |
* | |
* @param {*} eventName | |
* @param {*} eventData | |
* @param {*} eventScope | |
* @returns | |
* @memberof EventEngine | |
*/ | |
trigger(eventName, eventData, eventScope) { | |
if (!this.eventHandler[eventName]) return; | |
this.eventHandler[eventName].forEach((func) => { | |
if (typeof (func) === "function") { | |
// eventScope and eventData - when left undefined, will run OK | |
func.apply(eventScope, eventData); | |
} | |
}); | |
} | |
} | |
module.exports = EventEngine; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment