Last active
November 9, 2016 00:25
-
-
Save 10thfloor/434528d9794d4d5f5bcc3d6729360efa to your computer and use it in GitHub Desktop.
Simple event class
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 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