element-vir
Version:
Heroic. Reactive. Declarative. Type safe. Web components without compromise.
52 lines (51 loc) • 1.32 kB
JavaScript
/**
* A custom event with strict types for details and the event's `type` property.
*
* @category Internal
*/
export class TypedEvent extends CustomEvent {
_type;
get type() {
return this._type;
}
constructor(type, value) {
const eventType = typeof type === 'string' ? type : type.type;
super(eventType, {
detail: value,
bubbles: true,
composed: true,
});
this._type = eventType;
}
}
/**
* Define a stand-alone typed event that can be emitted and listened to inside of HTML templates.
*
* Make sure to use currying and call this function twice! (This is required by TypeScript's type
* parameter inference system.)
*
* @category Element Definition
* @example
*
* ```ts
* import {defineTypedEvent} from 'element-vir';
*
* const myCustomEvent = defineTypedEvent<number>()('my-custom-event');
*
* const myCustomEvent2 = defineTypedEvent<// the event's `.detail` type
* number>()(
* // the event's `.type` string
* 'my-custom-event2',
* );
* ```
*/
export function defineTypedEvent() {
return (eventType) => {
return class extends TypedEvent {
static type = eventType;
constructor(value) {
super(eventType, value);
}
};
};
}