Skip to content

事件 (Events)

ctx.events 是内置服务,提供了与事件系统相关的 API。

实例方法

ctx.on(event, listener, options?)

  • event: string 事件名称
  • listener: Function 事件监听器
  • options: object 事件监听器选项
    • prepend: boolean 是否注册为前置
    • global: boolean 是否注册为全局
  • 返回值: () => void 回收副作用

注册一个事件监听器。

ctx.emit(thisArg?, event, ...args)

ctx.parallel(thisArg?, event, ...args)

  • thisArg: any 事件监听器的 this 参数
  • event: string 事件名称
  • args: any[] 事件参数
  • 返回值: void | Promise<void>

同时触发所有 event 事件的能够匹配 thisArg 对象的监听器。

emit 为同步,parallel 为异步。

ctx.bail(thisArg?, event, ...args)

ctx.serial(thisArg?, event, ...args)

  • thisArg: any 事件监听器的 this 参数
  • event: string 事件名称
  • args: any[] 事件参数
  • 返回值: any

依次触发所有 event 事件的能够匹配 thisArg 对象的监听器。一旦某个监听器返回除 false, null, undefined 以外的值,将会停止后续监听器的执行并立即返回这个值。

bail 为同步,serial 为异步。

ctx.waterfall(thisArg?, event, ...args)

  • thisArg: any 事件监听器的 this 参数
  • event: string 事件名称
  • args: any[] 事件参数
  • 返回值: any

依次触发所有 event 事件的能够匹配 thisArg 对象的监听器。每个监听器内部将会决定是否调用下一个监听器。返回第一个监听器的返回值。

内置事件

'internal/plugin'(scope)

插件被加载或卸载时触发。

'internal/error'(format, ...params)

'internal/warn'(format, ...params)

'internal/info'(format, ...params)

  • 触发模式: emit
  • this: Context 上下文实例
  • format: string 格式化字符串
  • params: any[] 格式化参数

出现错误 / 警告 / 信息时触发。

如果没有注册对应的监听器,将会调用默认的 console.error / console.warn / console.info 进行输出。

'internal/dispatch'(mode, event, args, thisArg?)

  • 触发模式: emit
  • mode: DispatchMode 触发模式
  • event: string 事件名称
  • args: any[] 事件参数
  • thisArg: any 事件的 this 参数

任意非内置事件触发时触发。mode 类型如下:

ts
type 
DispatchMode
= 'emit' | 'bail' | 'parallel' | 'serial' | 'waterfall'

'internal/update'(scope, config) 实验性

  • 触发模式: bail
  • scope: EffectScope 插件作用域
  • config: any 新的插件配置
  • 返回值: boolean

插件配置更新时触发。返回 true 表示不需要重启插件。