Skip to content

Instantly share code, notes, and snippets.

@DroopyTersen
Last active November 3, 2017 21:16
Show Gist options
  • Select an option

  • Save DroopyTersen/cb6c8a0dd32878fd75735540fb68dd1d to your computer and use it in GitHub Desktop.

Select an option

Save DroopyTersen/cb6c8a0dd32878fd75735540fb68dd1d to your computer and use it in GitHub Desktop.
barebones ES6 Event Aggregator
class Eventer {
constructor() {
this.events = {};
}
ensureEvent(key) {
return this.events[key] || (this.events[key] = { subscriptions: [] });
}
on(key, cb) {
if (typeof cb !== "function") throw new Error("You must pass a function when you subscribe");
this.ensureEvent(key).subscriptions.push(cb);
}
trigger(key, ...args) {
this.ensureEvent(key)
.subscriptions
.forEach(s => setTimeout(() => s.apply(null, args), 0))
}
}
// EXAMPLE USAGE
var events = new Eventer();
var handler1 = (val) => {
console.log("Handler 1: " + val);
}
var handler2 = (val1, val2) => {
console.log("Handler 2: " + val1 + val2);
}
events.on("one", handler1);
events.on("two", handler2);
setTimeout(() => events.trigger("one", "hi there"), 100);
setTimeout(() => events.trigger("two", "I am arg1", " and i'm arg 2"), 200);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment