UNPKG

typed-event-target

Version:

EventTarget in the browser but with strong event typing.

33 lines (32 loc) 993 B
/** * Define an `Event` sub-class with a type tied to its event type string. Optionally accepts a * second parameter to specify a parent super class (must extend `Event`) instead of the default * `Event`. Defined events bubble and cross shadow boundaries by default. Explicit event init values * override these defaults. * * @category Events * @example * * ```ts * import {defineTypedEvent} from 'typed-event-target'; * * defineTypedEvent('event-type-string'); * * // with a custom super class * defineTypedEvent('event-type-string', MyCustomEvent); * ``` */ export function defineTypedEvent(type, SuperClass) { const ParentClass = SuperClass ?? Event; const TypedEventConstructor = class extends ParentClass { static type = type; constructor(eventInitDict) { super(type, { bubbles: true, composed: true, ...eventInitDict, }); } }; return TypedEventConstructor; }