JavaScript events for custom objects

Example

// 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();

See

interface ExternalControls {
    addEventListener<T>(type, listener): void;
    addEventListener<T>(type, listener): void;
    dispatchEvent<T>(event): void;
    hasEventListener<T>(type, listener): boolean;
    hasEventListener<T>(type, listener): boolean;
    removeEventListener<T>(type, listener): void;
    removeEventListener<T>(type, listener): 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