import {useRef, useState} from "react"; import type {ComponentEvent, ObjectEmitOptions} from "./emit.type"; import type {SimpleFunction} from "./event.type"; import {createPlainEvent} from 'plain-utils/utils/event'; /** * 创建setupEvent对象 * @author 韦胜健 * @date 2021/3/9 18:14 */ export function useEvent>(fcProps: any, emitsOptions?: T): { setupEvent: ComponentEvent } { const emitter = useRef({} as any); if (!!emitsOptions) { Object.keys(emitsOptions) .forEach(emitName => { emitter.current[emitName] !== fcProps[emitName] && (emitter.current[emitName] = fcProps[emitName]); if (emitName === 'onUpdateModelValue' && emitter.current.onChange !== fcProps.onChange) { emitter.current.onChange = fcProps.onChange; } }); } const [ret] = useState(() => { const event = createPlainEvent(); const emit = {} as any; const on = {} as any; const once = {} as any; const off = {} as any; if (!!emitsOptions) { const keys = Object.keys(emitsOptions); if (emitsOptions.onUpdateModelValue) {keys.push('onChange');} keys.forEach(key => { emit[key] = (...args: any[]) => { !!emitter.current[key] && emitter.current[key](...args); event.emit(key, ...args); if (key === 'onUpdateModelValue') { !!emitter.current.onChange && emitter.current.onChange(...args); event.emit('onChange', ...args); } }; on[key] = (fn: SimpleFunction) => event.on(key, fn); once[key] = (fn: SimpleFunction) => event.once(key, fn); off[key] = (fn: SimpleFunction) => event.off(key, fn); }); } return { emit, on, once, off }; }); return { setupEvent: ret }; }