All files / util/events TypedEventTarget.ts

55.55% Statements 5/9
100% Branches 0/0
16.66% Functions 1/6
62.5% Lines 5/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 674x 4x                                                         4x     4x                                                     4x            
const buildTypedEventTargetType = () => {
  const klass = class TypedEventTarget<EventMap> {
    addEventListener<K extends keyof EventMap>(
      type: K,
      listener: (this: HTMLElement, ev: EventMap[K]) => any,
      options?: boolean | AddEventListenerOptions,
    ): void;
    addEventListener(
      type: string,
      callback: EventListenerOrEventListenerObject | null,
      options?: AddEventListenerOptions | boolean,
    ): void;
    addEventListener(): void {}
    dispatchEvent(event: EventMap[keyof EventMap]): boolean;
    dispatchEvent(event: Event): boolean;
    dispatchEvent(): boolean {
      return true;
    }
    removeEventListener<K extends keyof EventMap>(
      type: K,
      listener: (this: HTMLElement, ev: EventMap[K]) => any,
      options?: boolean | EventListenerOptions,
    ): void;
    removeEventListener(
      type: string,
      callback: EventListenerOrEventListenerObject | null,
      options?: EventListenerOptions | boolean,
    ): void;
    removeEventListener(): void {}
  };
  return EventTarget as unknown as typeof klass;
};
 
export const TypedEventTarget = buildTypedEventTargetType();
 
export interface TypedEventTarget<EventMap> {
  addEventListener<K extends keyof EventMap>(
    type: K,
    listener: (this: HTMLElement, ev: EventMap[K]) => any,
    options?: boolean | AddEventListenerOptions,
  ): void;
  addEventListener(
    type: string,
    callback: EventListenerOrEventListenerObject | null,
    options?: AddEventListenerOptions | boolean,
  ): void;
  dispatchEvent(event: EventMap[keyof EventMap]): boolean;
  dispatchEvent(event: Event): boolean;
  removeEventListener<K extends keyof EventMap>(
    type: K,
    listener: (this: HTMLElement, ev: EventMap[K]) => any,
    options?: boolean | EventListenerOptions,
  ): void;
  removeEventListener(
    type: string,
    callback: EventListenerOrEventListenerObject | null,
    options?: EventListenerOptions | boolean,
  ): void;
}
 
export class SubscriptionEventTarget<EventMap> extends TypedEventTarget<EventMap> {
  public subscribe<K extends keyof EventMap>(type: K, listener: (ev: EventMap[K]) => void): () => void {
    this.addEventListener(type, listener);
    return () => this.removeEventListener(type, listener);
  }
}