typed-event-target
Version:
EventTarget in the browser but with strong event typing.
29 lines (28 loc) • 1.12 kB
JavaScript
/**
* Define a `CustomEvent` sub-class with a type tied to its detail type and event type string. This
* is the same as `defineTypedEvent` but with a detail property for storing arbitrary data.
*
* This needs to be called twice in order to properly bind both the detail type generic and the
* event type string. Defined events bubble and cross shadow boundaries by default. Explicit event
* init values override these defaults.
*
* @category Events
* @example DefineTypedCustomEvent<DetailType>()('event-type-string');
*/
export function defineTypedCustomEvent() {
/** Needs to be called with the type string in order to finalize the event definition setup. */
function defineEventTypeString(type) {
const TypedEventConstructor = class extends CustomEvent {
static type = type;
constructor(eventInitDict) {
super(type, {
bubbles: true,
composed: true,
...eventInitDict,
});
}
};
return TypedEventConstructor;
}
return defineEventTypeString;
}