Guest User

Untitled

a guest
Feb 17th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. /*
  2.  
  3. *** Publish/Subscribe global events functions - implementation of pubsub pattern for loose coupled components ***
  4.  
  5. Usage:
  6.  
  7. * Publish global application event:
  8.  
  9. publish("unique event name / category / subcategory", arg1, arg2, arg3);
  10. or
  11. publish(["event1", "event2", "event3"], arg1, arg2, arg3);
  12.  
  13.  
  14. * Subscribe to global application event:
  15. (as many subscribtions as neccessary)
  16.  
  17. subscribe("unique event name", (arg1, arg2, arg3) => { console.log("Do something useful on 'unique event name'..."); });
  18. or
  19. subscribe(["event1", "event2", "event3"], () => { console.log("Do something useful on those three events ..."); });
  20.  
  21.  
  22. * To unsubscribe from global application event:
  23. (which may be necessary on componentWillUnmount because react components can't update state when component isn't mounted)
  24.  
  25. let ref = subscribe("unique event name", (arg1, arg2, arg3) => { });
  26. unsubscribe("unique event name", ref);
  27.  
  28. unsubscribe will return true if event or events where unsubscribed
  29. */
  30. const
  31. _entries = {};
  32.  
  33. export const
  34. subscribe = (name, handler) => {
  35. const
  36. doSub = n => {
  37. let
  38. entry = _entries[n];
  39. if (!entry) {
  40. entry = _entries[n] = [];
  41. }
  42. return _entries[n].push(handler) - 1;
  43. };
  44. if (name instanceof Array) {
  45. let result = [];
  46. for(let i of name) {
  47. result.push({"name": i, index: doSub(i)});
  48. }
  49. return result;
  50. } else {
  51. return doSub(name);
  52. }
  53. };
  54.  
  55. export const
  56. unsubscribe = (name, ref) => {
  57. let
  58. result = false;
  59. if (ref instanceof Array === false) {
  60. ref = [{"name": name, index: ref}];
  61. }
  62. for(let item of ref) {
  63. let entry = _entries[item.name]
  64. if (!entry) {
  65. continue;
  66. }
  67. let index = entry.indexOf(item.index);
  68. if (index === -1) {
  69. continue;
  70. }
  71. entry.splice(index, 1);
  72. if (!result) {
  73. result = true;
  74. }
  75. }
  76. return result;
  77. };
  78.  
  79. export const
  80. publish = (name, ...args) => {
  81. const
  82. doPub = n => {
  83. const
  84. entry = _entries[n];
  85. if (!entry) {
  86. return;
  87. }
  88. entry.forEach(f => f.apply(this, args));
  89. };
  90. if (name instanceof Array) {
  91. for(let i of name) {
  92. doPub(i);
  93. }
  94. } else {
  95. doPub(name);
  96. }
  97. };
Add Comment
Please, Sign In to add comment