Skip to content

Instantly share code, notes, and snippets.

@panayotoff
Last active March 22, 2020 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save panayotoff/fc4978dd3d2b76dcfeb229f3d149df2e to your computer and use it in GitHub Desktop.
Save panayotoff/fc4978dd3d2b76dcfeb229f3d149df2e to your computer and use it in GitHub Desktop.
ES6 small event system in 30 LOC
/**
* 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