使用postal.js实现subEvent类似的观察者模式,让a.js事件发生后,执行b.js中的方法。
文档:https://www.awesomes.cn/repo/postaljs/postal-js
1.安装postal
npm install postal
2.介绍
subscribe (channel, topic, callback)
订阅事件或者说是注册事件,注册后,postal会通过channel和topic作为标识监听。该函数会返回一个handler,可以用于unsubscribe注销事件
channel:频道,注册的事件监听的频道,是topic的逻辑分区,可选值(postal有默认值)
topic:主题,事件的标识,在一个channel上应该是唯一的,需设置。
callback:回调函数,注册事件触发后需要执行的函数
publish(channel, topic,data, callback)
触发已经订阅的事件
channel:用以识别触发哪个channel
topic:用以识别频道上的那个topic
data:传递到subscribe回调函数的参数
callback:触发事件后的回调函数
unsubscribe(handler)
注销(取消订阅)事件
handler:subscribe的返回值,传入注销对应的事件
3.例子
- 公共方法 eventBus.js
import postal from 'postal'
export const eventBus = {
pub (channel, topic, data, callback) {
postal.publish(//触发
{
channel: channel,
topic: topic, // `${key}.${methodname}`,
data
},
callback
)
},
sub (channel, topic, callback) {
let handler = postal.subscribe({//订阅or注册?
channel: channel,
topic: topic,
callback
})
return handler
},
unsub (handler) {
postal.unsubscribe(handler)
},
}
- a.js 注册事件
import {eventBus} from '../../../util/eventBus.js';
const handle=eventBus.sub("ansToQue","updateTime",(data)=>{
console.log("eventBus sub 执行啦!");
console.log(data);
})
- b.js 触发事件
import {eventBus} from '../../../util/eventBus.js';
eventBus.pub("ansToQue","updateTime",{dd:110},()=>{
console.log("pub");
})