Created
February 6, 2019 18:56
-
-
Save jonathanlurie/06a2fe891e0747976a80623b12d41558 to your computer and use it in GitHub Desktop.
A simple way to deal with events (no event deleting yet)
This file contains 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
/** | |
* The EventManager deals with events, create them, call them. | |
* This class is mostly for being inherited from. | |
*/ | |
class EventManager { | |
/** | |
* Constructor | |
*/ | |
constructor() { | |
this._events = {} | |
} | |
/** | |
* Define an event, with a name associated with a function | |
* @param {String} eventName - Name to give to the event | |
* @param {Function} callback - function associated to the even | |
*/ | |
on(eventName, callback) { | |
if (typeof callback === 'function') { | |
if (!(eventName in this._events)) { | |
this._events[eventName] = [] | |
} | |
this._events[eventName].push(callback) | |
} else { | |
console.warn('The callback must be of type Function') | |
} | |
} | |
emit(eventName, args = []) { | |
// the event must exist and be non null | |
if ((eventName in this._events) && (this._events[eventName].length > 0)) { | |
const events = this._events[eventName] | |
for (let i = 0; i < events.length; i += 1) { | |
events[i](...args) | |
} | |
} else { | |
console.warn(`No function associated to the event ${eventName}`) | |
} | |
} | |
} | |
export default EventManager |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment