index.uts 1.7 KB
Newer Older
DCloud-yyl's avatar
DCloud-yyl 已提交
1
import {
DCloud-yyl's avatar
DCloud-yyl 已提交
2 3
    Emitter,
    getCurrentMP
DCloud-yyl's avatar
DCloud-yyl 已提交
4 5
} from '@dcloudio/uni-runtime'
import {
DCloud-yyl's avatar
DCloud-yyl 已提交
6 7
    $Emit,
    $Off,
DCloud-yyl's avatar
DCloud-yyl 已提交
8 9 10 11
    $On,
    $Once,
} from '../interface.uts'
import {
DCloud-yyl's avatar
DCloud-yyl 已提交
12 13
    API_$_EMIT,
    API_$_OFF,
DCloud-yyl's avatar
DCloud-yyl 已提交
14 15 16 17 18 19 20
    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 已提交
21
    off: (eventName: string, callback?: Function | null) => void
DCloud-yyl's avatar
DCloud-yyl 已提交
22 23 24
    emit: (eventName: string, ...args: (Object | undefined | null)[]) => void
}

DCloud-yyl's avatar
DCloud-yyl 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
const emitterStore = new Map<string, IUniEventEmitter>()

function getEmitter(): IUniEventEmitter {
    const mp = getCurrentMP()
    const id = mp.id as string
    if (emitterStore.has(id)) {
        return emitterStore.get(id) as IUniEventEmitter
    }
    const emitter = new Emitter() as IUniEventEmitter
    emitterStore.set(id, emitter)
    mp.on('beforeClose', () => {
        emitterStore.delete(id)
    })
    return emitter
}
DCloud-yyl's avatar
DCloud-yyl 已提交
40

DCloud-yyl's avatar
DCloud-yyl 已提交
41
export const $on: $On = defineSyncApi<number>(
DCloud-yyl's avatar
DCloud-yyl 已提交
42 43
    API_$_ON,
    (eventName: string, callback: Function) => {
DCloud-yyl's avatar
DCloud-yyl 已提交
44
        return getEmitter().on(eventName, callback)
DCloud-yyl's avatar
DCloud-yyl 已提交
45 46 47
    }
) as $On

DCloud-yyl's avatar
DCloud-yyl 已提交
48
export const $once: $Once = defineSyncApi<number>(
DCloud-yyl's avatar
DCloud-yyl 已提交
49 50
    API_$_ONCE,
    (eventName: string, callback: Function) => {
DCloud-yyl's avatar
DCloud-yyl 已提交
51
        return getEmitter().once(eventName, callback)
DCloud-yyl's avatar
DCloud-yyl 已提交
52 53 54 55 56 57
    }
) as $Once

export const $off: $Off = defineSyncApi<void>(
    API_$_OFF,
    (eventName: string, callback: Function) => {
DCloud-yyl's avatar
DCloud-yyl 已提交
58
        getEmitter().off(eventName, callback)
DCloud-yyl's avatar
DCloud-yyl 已提交
59 60 61 62 63 64
    }
) as $Off

export const $emit: $Emit = defineSyncApi<void>(
    API_$_EMIT,
    (eventName: string, ...args: (Object | undefined | null)[]) => {
DCloud-yyl's avatar
DCloud-yyl 已提交
65
        getEmitter().emit(eventName, ...args)
DCloud-yyl's avatar
DCloud-yyl 已提交
66 67
    }
) as $Emit