|
1 |
| -import { intercept, Ctrl, Ctx } from 'js-element' |
| 1 | +import { intercept, Ctrl, Ctx, Listener } from 'js-element' |
2 | 2 |
|
3 | 3 | // === data ==========================================================
|
4 | 4 |
|
@@ -211,22 +211,52 @@ export const useStyles = hook('useStyles', (...styles: string[]) => {
|
211 | 211 |
|
212 | 212 | // === useEmitter ======================================================
|
213 | 213 |
|
214 |
| -export const useEmitter = hook('useEmitter', function (): < |
215 |
| - E extends CustomEvent<any> |
216 |
| ->( |
217 |
| - ev: E, |
218 |
| - handler?: (ev: E) => void |
219 |
| -) => void { |
220 |
| - const host = currentCtrl!.getHost() |
| 214 | +function useEmitterFn(): (ev: CustomEvent<any>) => void |
| 215 | +function useEmitterFn<D = void>(type: string): (detail: D) => void |
| 216 | +function useEmitterFn<T extends string, D>( |
| 217 | + type: T, |
| 218 | + getEventProp: () => Listener<CustomEvent<D> & { type: T }> | undefined |
| 219 | +): (detail: D) => void |
221 | 220 |
|
222 |
| - return (ev, handler?) => { |
223 |
| - host.dispatchEvent(ev) |
| 221 | +function useEmitterFn(type?: string, getEventProp?: Function) { |
| 222 | + const host = useHost() |
| 223 | + |
| 224 | + if (arguments.length > 0 && typeof type !== 'string') { |
| 225 | + throw new Error('[useEmitter] Invalid type of first argument') |
| 226 | + } |
| 227 | + |
| 228 | + if (type === undefined) { |
| 229 | + return (ev: CustomEvent<any>) => host.dispatchEvent(ev) |
| 230 | + } |
224 | 231 |
|
225 |
| - if (handler) { |
226 |
| - handler(ev) |
| 232 | + if (getEventProp) { |
| 233 | + const eventListener = (ev: Event) => { |
| 234 | + const eventProp = getEventProp() |
| 235 | + |
| 236 | + eventProp && eventProp(ev) |
227 | 237 | }
|
| 238 | + |
| 239 | + useAfterMount(() => { |
| 240 | + host.addEventListener(type, eventListener) |
| 241 | + |
| 242 | + return () => host.removeEventListener(type, eventListener) |
| 243 | + }) |
228 | 244 | }
|
229 |
| -}) |
| 245 | + |
| 246 | + return <D>(detail: D, options?: CustomEventInit<D>) => { |
| 247 | + const ev = new CustomEvent<D>(type, { |
| 248 | + bubbles: true, |
| 249 | + composed: true, |
| 250 | + cancelable: true, |
| 251 | + ...options, |
| 252 | + detail |
| 253 | + }) |
| 254 | + |
| 255 | + host.dispatchEvent(ev) |
| 256 | + } |
| 257 | +} |
| 258 | + |
| 259 | +export const useEmitter = hook('useEmitter', useEmitterFn) |
230 | 260 |
|
231 | 261 | // === useMemo =========================================================
|
232 | 262 |
|
|
0 commit comments