@kinngyo/event-emitter
v0.0.5
Published
轻量事件派发器,支持基础事件监听、一次性监听、移除监听,以及 `all` / `any` 组合事件
Downloads
82
Readme
@kinngyo/event-emitter
轻量事件派发器,支持基础事件监听、一次性监听、移除监听,以及 all / any 组合事件。
安装
npm install @kinngyo/event-emitteryarn add @kinngyo/event-emitter导入
import EventEmitter from '@kinngyo/event-emitter'CommonJS:
const EventEmitterModule = require('@kinngyo/event-emitter')
const EventEmitter = EventEmitterModule.default || EventEmitterModule基本使用
import EventEmitter from '@kinngyo/event-emitter'
const emitter = new EventEmitter()
emitter.on('message', data => {
console.log(data)
})
emitter.emit('message', { text: 'hello' })绑定 this
构造函数可以传入 thisArg,监听函数执行时会使用它作为 this。
const context = { name: 'event-context' }
const emitter = new EventEmitter(context)
emitter.on('ready', function () {
console.log(this.name)
})
emitter.emit('ready')API
new EventEmitter(thisArg?)
创建事件派发器实例。
| 参数 | 类型 | 必填 | 说明 |
| ---- | ---- | ---- | ---- |
| thisArg | unknown | 否 | 监听函数执行时的 this |
emitter.on(target, callback)
注册事件监听。
emitter.on('change', value => {
console.log(value)
})target 支持字符串、Symbol,也支持数组批量注册。
emitter.on(['open', 'close'], event => {
console.log(event)
})emitter.once(target, callback)
注册只触发一次的监听。
emitter.once('ready', data => {
console.log(data)
})
emitter.emit('ready', 1)
emitter.emit('ready', 2)上面代码只会输出 1。
emitter.emit(target, ...params)
触发事件。
emitter.emit('change', 1, 2, 3)监听函数会按注册顺序执行。
emitter.on('change', (a, b, c) => {
console.log(a, b, c)
})
emitter.emit('change', 1, 2, 3)target 也支持数组,表示依次触发多个事件。
emitter.emit(['open', 'close'], 'done')emitter.off(target?, callback?)
移除监听。
不传参数时,移除全部监听。
emitter.off()只传 target 时,移除该事件的全部监听。
emitter.off('change')同时传 target 和 callback 时,只移除匹配的监听。
const listener = data => {
console.log(data)
}
emitter.on('change', listener)
emitter.off('change', listener)once 注册的监听也可以通过原 callback 移除。
const listener = data => {
console.log(data)
}
emitter.once('change', listener)
emitter.off('change', listener)组合事件
EventEmitter.all(targets, callback)
等待所有目标事件都触发后执行回调。
const task = EventEmitter.all(['user', 'config'], (user, config) => {
console.log(user, config)
})
task.emit('user', { id: 1 })
task.emit('config', { theme: 'dark' })回调参数顺序与 targets 顺序一致。
EventEmitter.any(targets, callback)
任意一个目标事件触发后执行回调。
const task = EventEmitter.any(['success', 'error'], result => {
console.log(result)
})
task.emit('success', 'ok')all 和 any 返回的是轻量派发对象,只提供 emit 方法。
any 的组合事件只会等待事件触发成功,不包含失败分支;因此内部使用“第一个完成”的语义实现,保持 ES2020 产物目标。
类型
type EventEmitterTarget = string | symbol | Array<string | symbol>
type EventEmitterStaticTarget = Array<string | symbol>
type EventEmitterCallback = (...args: unknown[]) => void
interface EventEmitterTrigger {
emit(target: EventEmitterTarget, ...params: unknown[]): void
}注意事项
target必须是string、symbol或它们组成的数组。off(target, callback)每次只移除一个匹配的监听。emit触发不存在的事件时不会报错。EventEmitter.version是构建时写入的版本号。- 当前构建目标为 ES2020。
