All files / common subscribe.ts

76.47% Statements 13/17
70% Branches 7/10
80% Functions 4/5
86.67% Lines 13/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  1x               1x   1x 1x     1x 1x 1x 1x     1x 1x 1x 1x   1x                
import { EVENTTYPES, WxEvents } from './constant'
import { getFlag, getFunctionName, logger, nativeTryCatch, setFlag } from '../utils'
export interface ReplaceHandler {
  type: EVENTTYPES | WxEvents
  callback: ReplaceCallback
}
 
type ReplaceCallback = (data: any) => void
 
const handlers: { [key in EVENTTYPES]?: ReplaceCallback[] } = {}
 
export function subscribeEvent(handler: ReplaceHandler): void {
  Iif (!handler) {
    return
  }
  Iif (getFlag(handler.type)) return
  setFlag(handler.type, true)
  handlers[handler.type] = handlers[handler.type] || []
  handlers[handler.type].push(handler.callback)
}
 
export function triggerHandlers(type: EVENTTYPES | WxEvents, data: any): void {
  Iif (!type || !handlers[type]) return
  handlers[type].forEach((callback) => {
    nativeTryCatch(
      () => {
        callback(data)
      },
      (e: Error) => {
        logger.error(`重写事件triggerHandlers的回调函数发生错误\nType:${type}\nName: ${getFunctionName(callback)}\nError: ${e}`)
      }
    )
  })
}