Skip to content

Instantly share code, notes, and snippets.

@willishq
Last active October 10, 2015 22:06
Show Gist options
  • Save willishq/feda4575ed0b8b7d2339 to your computer and use it in GitHub Desktop.
Save willishq/feda4575ed0b8b7d2339 to your computer and use it in GitHub Desktop.
Simple ES6 Event Bus implementation
class Listeners {
constructor() {
this.list = {};
}
create(eventName, id, cb) {
if (!this.list[eventName]) {
this.list[eventName] = {};
}
this.list[eventName][id] = cb;
}
destroy(eventName, id) {
delete this.list[eventName][id];
}
fire(eventName, args) {
_.each(this.list[eventName], cb => {
cb.apply(window, args);
});
}
}
class EventBus {
constructor() {
this.listeners = new Listeners();
}
subscribe(eventName, id, cb, once) {
this.listeners.create(eventName, id, cb);
if (once) {
this.unsubscribe(eventName, id);
}
}
once(eventName, id, cb) {
this.subscribe(eventName, id, cb, true);
}
unsubscribe(eventName, id) {
this.listeners.destroy(eventName, id);
}
broadcast(eventName, args) {
this.listeners.fire(eventName, args);
}
}
export default new EventBus();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment