postal.js使用+例子

使用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");
})



 

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值