Created
November 3, 2016 15:43
-
-
Save thefringeninja/94d2127b7eef17007bca518ee5d09769 to your computer and use it in GitHub Desktop.
EnterpriseServiceBus in ES6
This file contains hidden or 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
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