event-handler.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. *
  3. * All objects in the event handling chain should inherit from this class
  4. *
  5. */
  6. import Event from './events';
  7. class EventHandler {
  8. constructor(wfs, ...events) {
  9. this.wfs = wfs;
  10. this.onEvent = this.onEvent.bind(this);
  11. this.handledEvents = events;
  12. this.useGenericHandler = true;
  13. this.registerListeners();
  14. }
  15. destroy() {
  16. this.unregisterListeners();
  17. }
  18. isEventHandler() {
  19. return typeof this.handledEvents === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';
  20. }
  21. registerListeners() {
  22. if (this.isEventHandler()) {
  23. this.handledEvents.forEach(function(event) {
  24. if (event === 'wfsEventGeneric') {
  25. //throw new Error('Forbidden event name: ' + event);
  26. }
  27. this.wfs.on(event, this.onEvent);
  28. }.bind(this));
  29. }
  30. }
  31. unregisterListeners() {
  32. if (this.isEventHandler()) {
  33. this.handledEvents.forEach(function(event) {
  34. this.wfs.off(event, this.onEvent);
  35. }.bind(this));
  36. }
  37. }
  38. /**
  39. * arguments: event (string), data (any)
  40. */
  41. onEvent(event, data) {
  42. this.onEventGeneric(event, data);
  43. }
  44. onEventGeneric(event, data) {
  45. var eventToFunction = function(event, data) {
  46. var funcName = 'on' + event.replace('wfs', '');
  47. if (typeof this[funcName] !== 'function') {
  48. //throw new Error(`Event ${event} has no generic handler in this ${this.constructor.name} class (tried ${funcName})`);
  49. }
  50. return this[funcName].bind(this, data);
  51. };
  52. try {
  53. eventToFunction.call(this, event, data).call();
  54. } catch (err) {
  55. console.log(`internal error happened while processing ${event}:${err.message}`);
  56. // this.hls.trigger(Event.ERROR, {type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event : event, err : err});
  57. }
  58. }
  59. }
  60. export default EventHandler;