Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. class MessageBus {
  2. constructor() {
  3. this.channels = {}
  4. }
  5.  
  6. subscribe(object) {
  7. if (this.channels[object.channel]) {
  8. if (this.channels[object.channel][object.topic]) {
  9. this.channels[object.channel][object.topic].push(object.callback);
  10. } else {
  11. this.channels[object.channel][object.topic] = [object.callback];
  12. }
  13. } else {
  14. let topic = {};
  15. topic[object.topic] = [object.callback];
  16. this.channels[object.channel] = topic;
  17. }
  18. }
  19.  
  20. publish(object) {
  21. if (this.channels[object.channel]) {
  22. if (this.channels[object.channel][object.topic]) {
  23. for (let i = 0; i < this.channels[object.channel][object.topic].length; i++) {
  24. this.channels[object.channel][object.topic][i](object.data);
  25. }
  26. }
  27. }
  28. }
  29. }
  30.  
  31. let messageBus = new MessageBus;
  32. messageBus.subscribe({ channel: 'hi', topic: 'logging', callback: (payload) => console.log(payload)});
  33. messageBus.subscribe({ channel: 'hey', topic: 'log', callback: (payload) => console.log(payload)});
  34. messageBus.subscribe({ channel: 'hey', topic: 'logging', callback: (payload) => console.log(payload)});
  35. messageBus.subscribe({ channel: 'hey', topic: 'logging', callback: (payload) => console.log(payload, payload)});
  36. 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