Last active
March 22, 2020 14:48
-
-
Save panayotoff/fc4978dd3d2b76dcfeb229f3d149df2e to your computer and use it in GitHub Desktop.
ES6 small event system in 30 LOC
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
/** | |
* Basic event system. Use in component or as event bus | |
* Author: Chris Panayotoff <chris.panayotoff[at]gmail[dot]com> | |
*/ | |
export default class Eventify { | |
constructor() { | |
this.list = {}; | |
} | |
trigger(event, eventObject = {}) { | |
eventObject._name = event; | |
if (!this.list[event]) return; | |
for (const handlerObject of this.list[event]) { | |
handlerObject.handler(eventObject); | |
handlerObject.once && this.off(event, handlerObject.handler); | |
} | |
} | |
on(event, handler, once = false) { | |
if (!this.list[event]) this.list[event] = []; | |
this.list[event].push({ once: once, handler: handler }); | |
} | |
once(event, handler) { | |
this.on(event, handler, true); | |
} | |
off(event, handler) { | |
if (!event) this.list = {}; | |
if (!this.list[event]) return; | |
if (!handler) this.list[event] = []; | |
const indexToRemove = this.list[event].findIndex( | |
eventObject => eventObject.handler === handler | |
); | |
indexToRemove > -1 && this.list[event].splice(indexToRemove, 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment