JavaScript events for custom objects

// Adding events to a custom object
class Car extends EventDispatcher {
start() {
this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
}
};
// Using events with the custom object
const car = new Car();
car.addEventListener( 'start', ( event ) => {
alert( event.message );
} );
car.start();
interface ExternalControls {
    addEventListener<T>(type: T, listener: EventListener<{
        change: unknown;
    }[T], T, ExternalControls>): void;
    addEventListener<T>(type: T, listener: EventListener<{}, T, ExternalControls>): void;
    dispatchEvent<T>(event: BaseEvent<T> & {
        change: unknown;
    }[T]): void;
    hasEventListener<T>(type: T, listener: EventListener<{
        change: unknown;
    }[T], T, ExternalControls>): boolean;
    hasEventListener<T>(type: T, listener: EventListener<{}, T, ExternalControls>): boolean;
    removeEventListener<T>(type: T, listener: EventListener<{
        change: unknown;
    }[T], T, ExternalControls>): void;
    removeEventListener<T>(type: T, listener: EventListener<{}, T, ExternalControls>): void;
    update(): void;
}

Hierarchy (view full)

Methods

  • Adds a listener to an event type.

    Type Parameters

    • T extends "change"

    Parameters

    • type: T

      The type of event to listen to.

    • listener: EventListener<{
          change: unknown;
      }[T], T, ExternalControls>

      The function that gets called when the event is fired.

    Returns void

  • Type Parameters

    • T extends string

    Parameters

    Returns void

  • Fire an event type.

    Type Parameters

    • T extends "change"

    Parameters

    • event: BaseEvent<T> & {
          change: unknown;
      }[T]

      The event that gets fired.

    Returns void

  • Checks if listener is added to an event type.

    Type Parameters

    • T extends "change"

    Parameters

    • type: T

      The type of event to listen to.

    • listener: EventListener<{
          change: unknown;
      }[T], T, ExternalControls>

      The function that gets called when the event is fired.

    Returns boolean

  • Type Parameters

    • T extends string

    Parameters

    Returns boolean

  • Removes a listener from an event type.

    Type Parameters

    • T extends "change"

    Parameters

    • type: T

      The type of the listener that gets removed.

    • listener: EventListener<{
          change: unknown;
      }[T], T, ExternalControls>

      The listener function that gets removed.

    Returns void

  • Type Parameters

    • T extends string

    Parameters

    Returns void