Skip to content

Instantly share code, notes, and snippets.

@thefringeninja
Created November 3, 2016 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thefringeninja/94d2127b7eef17007bca518ee5d09769 to your computer and use it in GitHub Desktop.
Save thefringeninja/94d2127b7eef17007bca518ee5d09769 to your computer and use it in GitHub Desktop.
EnterpriseServiceBus in ES6
class Bus {
constructor() {
this.handlers = {};
}
subscribe(type, handler) {
this.handlers[type] = (this.handlers[type] || [])
.concat(handler);
}
unsubcribe(type, handler) {
this.handlers[type] = (this.handlers[type] || [])
.filter(h => handler !== h);
}
publish(type, message) {
const handlers = this.handlers[type];
if (handlers) {
handlers.forEach(handler => handler(message));
}
const base = Object.getPrototypeOf(type);
return base && (this.publish(base, message) || !!handlers);
}
}
class Message {}
class Written extends Message {}
class Really extends Written {}
const writtenHandler = m => console.log(m.name);
const bus = new Bus();
bus.subscribe(Written, writtenHandler);
bus.subscribe(Really, m => console.log("rly"));
bus.subscribe(Message, m => console.log("lolz!"));
bus.publish(Really, {name: 'derp'});
bus.unsubcribe(Written, writtenHandler);
bus.publish(Really, {name: 'derp'});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment