Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class MessageBus {
- constructor() {
- this.channels = {}
- }
- subscribe(object) {
- if (this.channels[object.channel]) {
- if (this.channels[object.channel][object.topic]) {
- this.channels[object.channel][object.topic].push(object.callback);
- } else {
- this.channels[object.channel][object.topic] = [object.callback];
- }
- } else {
- let topic = {};
- topic[object.topic] = [object.callback];
- this.channels[object.channel] = topic;
- }
- }
- publish(object) {
- if (this.channels[object.channel]) {
- if (this.channels[object.channel][object.topic]) {
- for (let i = 0; i < this.channels[object.channel][object.topic].length; i++) {
- this.channels[object.channel][object.topic][i](object.data);
- }
- }
- }
- }
- }
- let messageBus = new MessageBus;
- messageBus.subscribe({ channel: 'hi', topic: 'logging', callback: (payload) => console.log(payload)});
- messageBus.subscribe({ channel: 'hey', topic: 'log', callback: (payload) => console.log(payload)});
- messageBus.subscribe({ channel: 'hey', topic: 'logging', callback: (payload) => console.log(payload)});
- messageBus.subscribe({ channel: 'hey', topic: 'logging', callback: (payload) => console.log(payload, payload)});
- messageBus.publish({ channel: 'hey', topic: 'logging', data: 'message'}); // last two subscribers get their stuff run in order
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement