Home Reference Source

src/event-handler.ts

  1. /*
  2. *
  3. * All objects in the event handling chain should inherit from this class
  4. *
  5. */
  6.  
  7. import { logger } from './utils/logger';
  8. import { ErrorTypes, ErrorDetails } from './errors';
  9. import Event from './events';
  10. import Hls from './hls';
  11.  
  12. const FORBIDDEN_EVENT_NAMES = {
  13. 'hlsEventGeneric': true,
  14. 'hlsHandlerDestroying': true,
  15. 'hlsHandlerDestroyed': true
  16. };
  17.  
  18. class EventHandler {
  19. hls: Hls;
  20. handledEvents: any[];
  21. useGenericHandler: boolean;
  22.  
  23. constructor (hls: Hls, ...events: any[]) {
  24. this.hls = hls;
  25. this.onEvent = this.onEvent.bind(this);
  26. this.handledEvents = events;
  27. this.useGenericHandler = true;
  28.  
  29. this.registerListeners();
  30. }
  31.  
  32. destroy () {
  33. this.onHandlerDestroying();
  34. this.unregisterListeners();
  35. this.onHandlerDestroyed();
  36. }
  37.  
  38. protected onHandlerDestroying () {}
  39. protected onHandlerDestroyed () {}
  40.  
  41. isEventHandler () {
  42. return typeof this.handledEvents === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';
  43. }
  44.  
  45. registerListeners () {
  46. if (this.isEventHandler()) {
  47. this.handledEvents.forEach(function (event) {
  48. if (FORBIDDEN_EVENT_NAMES[event]) {
  49. throw new Error('Forbidden event-name: ' + event);
  50. }
  51.  
  52. this.hls.on(event, this.onEvent);
  53. }, this);
  54. }
  55. }
  56.  
  57. unregisterListeners () {
  58. if (this.isEventHandler()) {
  59. this.handledEvents.forEach(function (event) {
  60. this.hls.off(event, this.onEvent);
  61. }, this);
  62. }
  63. }
  64.  
  65. /**
  66. * arguments: event (string), data (any)
  67. */
  68. onEvent (event: string, data: any) {
  69. this.onEventGeneric(event, data);
  70. }
  71.  
  72. onEventGeneric (event: string, data: any) {
  73. let eventToFunction = function (event: string, data: any) {
  74. let funcName = 'on' + event.replace('hls', '');
  75. if (typeof this[funcName] !== 'function') {
  76. throw new Error(`Event ${event} has no generic handler in this ${this.constructor.name} class (tried ${funcName})`);
  77. }
  78.  
  79. return this[funcName].bind(this, data);
  80. };
  81. try {
  82. eventToFunction.call(this, event, data).call();
  83. } catch (err) {
  84. logger.error(`An internal error happened while handling event ${event}. Error message: "${err.message}". Here is a stacktrace:`, err);
  85. this.hls.trigger(Event.ERROR, { type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event: event, err: err });
  86. }
  87. }
  88. }
  89.  
  90. export default EventHandler;