ChannelFeature.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // name: 'Channel' does not behave the same as Golang's channel construct; it
  2. // behaves more like an EventEmitter.
  3. class Channel {
  4. constructor () {
  5. this.listeners_ = [];
  6. }
  7. // compare(EventService): EventService has an 'on' method,
  8. // but it accepts a 'selector' argument to narrow the scope of events
  9. on (callback) {
  10. // wet: EventService also creates an object like this
  11. const det = {
  12. detach: () => {
  13. const idx = this.listeners_.indexOf(callback);
  14. if ( idx !== -1 ) {
  15. this.listeners_.splice(idx, 1);
  16. }
  17. }
  18. };
  19. this.listeners_.push(callback);
  20. return det;
  21. }
  22. emit (...a) {
  23. for ( const lis of this.listeners_ ) {
  24. lis(...a);
  25. }
  26. }
  27. }
  28. class ChannelFeature {
  29. install_in_instance (instance) {
  30. const channels = instance._get_merged_static_array('CHANNELS');
  31. instance.channels = {};
  32. for ( const name of channels ) {
  33. instance.channels[name] = new Channel(name);
  34. }
  35. }
  36. }
  37. module.exports = {
  38. ChannelFeature,
  39. };