element-vir
Version:
Heroic. Reactive. Declarative. Type safe. Web components without compromise.
51 lines (50 loc) • 1.29 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) {
super(typeof type === 'string' ? type : type.type, {
detail: value,
bubbles: true,
composed: true,
});
}
}
/**
* 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;
_type = eventType;
constructor(value) {
super(eventType, value);
}
};
};
}