Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. let pubSubInstance;
  2.  
  3. /**
  4. * The PubSub class servers as a singleton,
  5. * it's used by the EventDispatcher class
  6. * (don't instantiate this class directly)
  7. */
  8. class PubSub {
  9. constructor() {
  10. if (!pubSubInstance) {
  11. this.subjects = {};
  12. this.hOP = this.subjects.hasOwnProperty;
  13. pubSubInstance = this;
  14. }
  15.  
  16. return pubSubInstance;
  17. }
  18.  
  19. /**
  20. *
  21. * @param {string} topic The event name
  22. * @param {function} callback Function to bind to the event
  23. * @return {PubSub} The PubSub singleton instance
  24. */
  25. on(topic, callback) {
  26. const { subjects, hOP } = this;
  27. if (!hOP.call(subjects, topic)) {
  28. subjects[topic] = [];
  29. }
  30.  
  31. subjects[topic].push(callback);
  32.  
  33. return this;
  34. }
  35.  
  36. /**
  37. *
  38. * @param {string} topic The event name
  39. * @param {function} callback Function to un-bind from the event
  40. * @return {PubSub} The PubSub singleton instance
  41. */
  42. off(topic, callback) {
  43. const { subjects } = this;
  44. if (subjects[topic] && subjects[topic].length) {
  45. const idx = subjects[topic].indexOf(callback);
  46. if (idx !== -1) {
  47. subjects[topic].splice(idx, 1);
  48. }
  49. }
  50.  
  51. return this;
  52. }
  53.  
  54. /**
  55. *
  56. * @param {string} topic The event name
  57. * @param {object} data Extra data to pass with the event
  58. * @return {PubSub|null} The PubSub singleton instance
  59. */
  60. trigger(topic, data) {
  61. const { subjects, hOP } = this;
  62. if (!hOP.call(subjects, topic)) {
  63. return null;
  64. }
  65.  
  66. subjects[topic].forEach((entry) => {
  67. if (entry) {
  68. entry(data !== undefined ? data : {});
  69. }
  70. });
  71.  
  72. return this;
  73. }
  74. }
  75.  
  76. /**
  77. * The EventDispatcher class servers as a global event dispatcher,
  78. * it uses the PubSub singleton class
  79. */
  80. export default class EventDispatcher {
  81. constructor() {
  82. this.pubSub = new PubSub();
  83. }
  84.  
  85. /**
  86. *
  87. * Please read the {@link PubSub.on} specs
  88. */
  89. on(...args) {
  90. return this.pubSub.on(...args);
  91. }
  92.  
  93. /**
  94. *
  95. * Please read the {@link PubSub.off} specs
  96. */
  97. off(...args) {
  98. return this.pubSub.off(...args);
  99. }
  100.  
  101. /**
  102. *
  103. * Please read the {@link PubSub.trigger} specs
  104. */
  105. trigger(...args) {
  106. return this.pubSub.trigger(...args);
  107. }
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement