Skip to content

Instantly share code, notes, and snippets.

@10thfloor
Last active November 9, 2016 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 10thfloor/434528d9794d4d5f5bcc3d6729360efa to your computer and use it in GitHub Desktop.
Save 10thfloor/434528d9794d4d5f5bcc3d6729360efa to your computer and use it in GitHub Desktop.
Simple event class
export default class Event {
constructor() {
this.handlers = []
}
emit(event, ...args) {
if(this.handlers.event) {
this.handlers[event].forEach((handler, index) => {
handler.apply(this, [...args])
});
}
}
on(event, callback) {
if(!this.handlers[event]) {
this.handlers[event] = [];
}
this.handlers[event].push(callback);
}
once(event, callback) {
const once = (...args) => {
callback.apply(this, [...args]);
this.removeListener(event, once);
}
this.on(event, once);
}
removeListener(event, callback) {
if(this.handlers[event]) {
const index = this.handlers[event].indexOf(callback)
this.handlers[event].splice(index, 1);
}
}
removeAllListeners(event) {
this.handlers[event] = undefined;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment