index.uts 1.2 KB
Newer Older
DCloud-yyl's avatar
DCloud-yyl 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
import {
    Emitter
} from '@dcloudio/uni-runtime'
import {
    $On,
    $Once,
    $Off,
    $Emit,
} from '../interface.uts'
import {
    API_$_ON,
    API_$_ONCE,
    API_$_OFF,
    API_$_EMIT,
} from '../protocol.uts'

interface IUniEventEmitter {
    on: (eventName: string, callback: Function) => void
    once: (eventName: string, callback: Function) => void
    off: (eventName: string, callback: Function) => void
    emit: (eventName: string, ...args: (Object | undefined | null)[]) => void
}

const emitter: IUniEventEmitter = new Emitter() as IUniEventEmitter

export const $on: $On = defineSyncApi<void>(
    API_$_ON,
    (eventName: string, callback: Function) => {
        emitter.on(eventName, callback)
    }
) as $On

export const $once: $Once = defineSyncApi<void>(
    API_$_ONCE,
    (eventName: string, callback: Function) => {
        emitter.once(eventName, callback)
    }
) 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