Skip to content

Instantly share code, notes, and snippets.

@xbenjii
Created February 6, 2017 11:55
Show Gist options
  • Save xbenjii/013297d9286016a3efb7772578117934 to your computer and use it in GitHub Desktop.
Save xbenjii/013297d9286016a3efb7772578117934 to your computer and use it in GitHub Desktop.
Tiny Event Emitter
/**
* 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