index.uts 1.3 KB
Newer Older
DCloud-yyl's avatar
DCloud-yyl 已提交
1 2 3 4
import {
    Emitter
} from '@dcloudio/uni-runtime'
import {
DCloud-yyl's avatar
DCloud-yyl 已提交
5 6
    $Emit,
    $Off,
DCloud-yyl's avatar
DCloud-yyl 已提交
7 8 9 10
    $On,
    $Once,
} from '../interface.uts'
import {
DCloud-yyl's avatar
DCloud-yyl 已提交
11 12
    API_$_EMIT,
    API_$_OFF,
DCloud-yyl's avatar
DCloud-yyl 已提交
13 14 15 16 17 18 19
    API_$_ON,
    API_$_ONCE,
} from '../protocol.uts'

interface IUniEventEmitter {
    on: (eventName: string, callback: Function) => void
    once: (eventName: string, callback: Function) => void
DCloud-yyl's avatar
DCloud-yyl 已提交
20
    off: (eventName: string, callback?: Function | null) => void
DCloud-yyl's avatar
DCloud-yyl 已提交
21 22 23 24 25
    emit: (eventName: string, ...args: (Object | undefined | null)[]) => void
}

const emitter: IUniEventEmitter = new Emitter() as IUniEventEmitter

DCloud-yyl's avatar
DCloud-yyl 已提交
26
export const $on: $On = defineSyncApi<number>(
DCloud-yyl's avatar
DCloud-yyl 已提交
27 28
    API_$_ON,
    (eventName: string, callback: Function) => {
DCloud-yyl's avatar
DCloud-yyl 已提交
29
        return emitter.on(eventName, callback)
DCloud-yyl's avatar
DCloud-yyl 已提交
30 31 32
    }
) as $On

DCloud-yyl's avatar
DCloud-yyl 已提交
33
export const $once: $Once = defineSyncApi<number>(
DCloud-yyl's avatar
DCloud-yyl 已提交
34 35
    API_$_ONCE,
    (eventName: string, callback: Function) => {
DCloud-yyl's avatar
DCloud-yyl 已提交
36
        return emitter.once(eventName, callback)
DCloud-yyl's avatar
DCloud-yyl 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
    }
) as $Once

export const $off: $Off = defineSyncApi<void>(
    API_$_OFF,
    (eventName: string, callback: Function) => {
        emitter.off(eventName, callback)
    }
) as $Off

export const $emit: $Emit = defineSyncApi<void>(
    API_$_EMIT,
    (eventName: string, ...args: (Object | undefined | null)[]) => {
        emitter.emit(eventName, ...args)
    }
) as $Emit