Created
February 6, 2017 11:55
-
-
Save xbenjii/013297d9286016a3efb7772578117934 to your computer and use it in GitHub Desktop.
Tiny Event Emitter
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
/** | |
* TinyEE - A tiny event emitter using Map. | |
*/ | |
class TinyEE { | |
constructor() { | |
// Where we will store the events | |
this.events = new Map(); | |
} | |
on(eventName, action) { | |
if(typeof action !== 'function') { | |
throw new Error(`Event ${eventName} must be a function, got ${typeof action}.`); | |
} | |
// Set the event with it's callback in the map | |
this.events.set(eventName, action); | |
} | |
emit(eventName, ...args) { | |
// Return the callback function so we can call it | |
const event = this.events.get(eventName); | |
if(typeof event !== 'function') { | |
throw new Error(`Event ${eventName} doesn't exist.`); | |
} | |
// Call the function with the passed arguments | |
eventToCall.apply(null, args); | |
} | |
remove(event) { | |
// Remove the event from our Map, returns false if it doesn't exist | |
return this.events.delete(event); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment