Skip to content

@neosjs/emitter ​

简易的事件订阅 / 发布器(EventEmitter),除常规的单窗口事件通信外,还支持基于广播通道的多窗口同步消息——一个浏览器窗口里发布的事件,其它同名通道的窗口也能收到。提供完整的 TypeScript 类型。

安装 ​

sh
pnpm add @neosjs/emitter
sh
npm i @neosjs/emitter
sh
yarn add @neosjs/emitter

快速上手 ​

基础使用 ​

ts
import NeosEmitter from '@neosjs/emitter'

const emitter = new NeosEmitter()

// 订阅
emitter.on('test', (data) => {
  console.log(data)
})

// 发布
emitter.emit('test', 'hello world')

多窗口同步 ​

创建实例时开启 broadcast,多个窗口使用相同的 channelName 即可互通消息:

ts
import NeosEmitter from '@neosjs/emitter'

const emitter = new NeosEmitter({
  channelName: 'neosjs', // 通道名称(默认值:@neosjs-broadcast-emitterevent)
  broadcast: true, // 是否开启广播(多窗口同步消息)
  debug: true // 是否开启调试(默认值:false)
})

// 窗口 B 订阅、监听事件
emitter.on('test', (data) => {
  console.log(data)
})

// 窗口 A 发布事件
emitter.emit('test', 'hello world')

API ​

构造参数 ​

new NeosEmitter(options: EmitterOptions) ​

参数说明类型默认值
options配置项EmitterOptions{}
options.channelName通道名称string@neosjs-broadcast-emitterevent
options.broadcast是否开启广播booleanfalse
options.debug是否开启调试booleanfalse

实例方法 ​

on(event: string, listener: Function) ​

订阅事件。

参数说明类型
event事件名称string
listener事件监听器Function

once(event: string, listener: Function) ​

订阅一次事件,触发后自动取消。

参数说明类型
event事件名称string
listener事件监听器Function

emit(event: string, data: any) ​

发布事件。

参数说明类型
event事件名称string
data事件数据any

off(event: string, listener?: Function) ​

取消订阅事件。

参数说明类型
event事件名称string
listener事件监听器(可选)Function

destroy() ​

销毁实例。