Skip to content

Commit 3bdeb59

Browse files
author
arnoson
committed
feat: pass CustomEvent directly
1 parent 164df09 commit 3bdeb59

File tree

3 files changed

+12
-17
lines changed

3 files changed

+12
-17
lines changed

src/mountComponent.ts

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,6 @@ import { getRefs } from './refs'
33
import { getComponent } from './registerComponent'
44
import { SimpleComponentEvent, SimpleElement } from './types'
55

6-
/**
7-
* Just a little syntactic sugar for `CustomEvent`. Passed to the component's
8-
* context as the fully typed `ComponentEvent`.
9-
* */
10-
export class CustomEventFactory {
11-
constructor(name: string, detail?: any) {
12-
return new CustomEvent(name, { detail })
13-
}
14-
}
15-
166
const mountChildComponents = (el: HTMLElement) => {
177
const elements = el.querySelectorAll<HTMLElement>('[data-simple-component]')
188
for (let i = 0; i < elements.length; i++) {
@@ -35,7 +25,7 @@ export const mountComponent = (el: HTMLElement, isChild = false) => {
3525
: el.dataset
3626

3727
const { refs, refsAll } = getRefs(el)
38-
const ComponentEvent = CustomEventFactory as SimpleComponentEvent
28+
const ComponentEvent = CustomEvent as SimpleComponentEvent
3929
const ctx = { el, props, refs, refsAll, ComponentEvent }
4030

4131
simpleEl.$props = props

src/types.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
interface CustomEventInitRequired<T = any> extends CustomEventInit {
2+
detail: T
3+
}
4+
15
type HTMLElementConstructor = typeof HTMLElement
26

37
type HTMLElementType<T extends HTMLElementConstructor> = T['prototype']
@@ -72,12 +76,14 @@ export type SimpleEventMap<Definitions> = {
7276
: CustomEvent<Definitions[K]>
7377
}
7478

75-
export type SimpleComponentEvent<
79+
export interface SimpleComponentEvent<
7680
Events extends Record<string, CustomEvent> = any
77-
> = {
78-
new <K extends keyof Events, Detail = Events[K]['detail']>(
81+
> extends CustomEvent {
82+
new <K extends keyof Events>(
7983
name: string,
80-
...args: Detail extends undefined | null ? [] : [detail: Detail]
84+
...args: Events[K]['detail'] extends undefined | null
85+
? [eventInitDict?: CustomEventInit]
86+
: [eventInitDict: CustomEventInitRequired<Events[K]['detail']>]
8187
): Events[K]
8288
}
8389

tests/index.test.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import {
55
registerComponent,
66
SimpleElement
77
} from '../src'
8-
import { CustomEventFactory } from '../src/mountComponent'
98

109
it('mounts a component', () => {
1110
const setup = vi.fn()
@@ -20,7 +19,7 @@ it('mounts a component', () => {
2019
refs: {},
2120
refsAll: {},
2221
props: div.dataset,
23-
ComponentEvent: CustomEventFactory
22+
ComponentEvent: CustomEvent
2423
})
2524
})
2625

0 commit comments

Comments
 (0)