Skip to content

Instantly share code, notes, and snippets.

@xbenjii xbenjii/TinyEE.js
Created Feb 6, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.