eventual-context.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /** Concept each channel can have child channels ??**/
  2. var EventualChannel = require('./eventual-channel');
  3. class EventualContext2 extends EventualChannel {
  4. constructor(eventual) {
  5. super(eventual);
  6. }
  7. broadcast(name,...args) {
  8. // Special send to all eventual contexts
  9. var tocall = [];
  10. this.eventual._events.ctx.forEach((c) => {
  11. tocall.push(...c.search(name));
  12. });
  13. return this.process(tocall,args)
  14. }
  15. state(name,...args) {
  16. this.eventual.state(name,args);
  17. }
  18. destroy() {
  19. this.childs = null;
  20. this.listeners = null;
  21. var i = this.eventual._events.ctx.indexOf(this);
  22. if(i!=-1) this.eventual._events.ctx.splice(i,1);
  23. }
  24. toString() {
  25. var out = [];
  26. this.eventual._events.ctx.forEach((c) => {
  27. var cur = c;
  28. // First level
  29. function listChild(cur,prefix) {
  30. for( var c in cur.childs) {
  31. var name = (prefix)?prefix + ":" + c:c;
  32. out.push(name);
  33. listChild(cur.childs[c], name);
  34. }
  35. }
  36. listChild(cur,"");
  37. });
  38. return out.join("\n");
  39. }
  40. }
  41. /** Old and deprecated **/
  42. class EventualContext extends EventualChannel {
  43. constructor(eventual) {
  44. super();
  45. this.eventual = eventual;
  46. // Contextual listeners, it will invalidate regexp?
  47. this.listeners = [];
  48. }
  49. process(tocall,args,donecb) {
  50. tocall.forEach((l) => {
  51. l.callback(...args);
  52. });
  53. }
  54. broadcast(name,...args) {
  55. this.eventual._events.ctx.forEach((c) => {
  56. c.emit(name,...args);
  57. });
  58. }
  59. /** flat model **/
  60. on(name,cb) {
  61. // Any listener will be placed here
  62. this.listeners.push({
  63. name: name,
  64. callback:cb
  65. });
  66. return this;
  67. }
  68. emit(name,...args) {
  69. // We need to go trought all contexts in Eventual
  70. var tocall = [];
  71. this.eventual._events.ctx.forEach((c) => {
  72. c.listeners.forEach((l) => {
  73. if(l.name == name) {
  74. tocall.push(l);
  75. }
  76. })
  77. });
  78. this.process(tocall,name,args);
  79. }/**/
  80. destroy() {
  81. var i = this.eventual._events.ctx.indexOf(this);
  82. if(i!=-1) this.eventual._events.ctx.splice(i,1);
  83. this.listeners = null;
  84. }
  85. }
  86. module.exports = EventualContext2;