Created
August 11, 2017 11:43
-
-
Save brunocarvalhodearaujo/6d0051ed0758872daf5f22388c9ac704 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
export class EventManager { | |
constructor () { | |
/** | |
* @type {{ [name:string]: Array<Function> }} | |
*/ | |
this.events = {} | |
} | |
/** | |
* @param {string} name | |
* @param {Function} middleware | |
*/ | |
on (name, middleware) { | |
if (typeof middleware !== 'function') { | |
throw new Error('middleware requires an function') | |
} | |
if (!this.events.hasOwnProperty(name)) { | |
this.events[ name ] = [] | |
} | |
this.events[ name ].push(middleware) | |
} | |
/** | |
* @param {string} name | |
* @param {...any} values | |
*/ | |
emit (name, ...values) { | |
if (!this.events.hasOwnProperty(name)) { | |
return undefined | |
} | |
this.events[name].forEach(middleware => middleware(...values)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment