使用postal.js实现subEvent类似的观察者模式,让a.js事件发生后,执行b.js中的方法。
1.安装postal
npm install postal
2.subscribe (channel, topic,callback)
订阅事件或者说注册事件
channel:频道,注册的事件监听的频道,是topic的逻辑分区,可选值
topic:主题,事件的标识,在一个channel上是唯一的,需设置
callback:回调函数,注册事件触发后需要执行的函数
var subscription = parent.postal.subscribe({
channel: "dispatch",
topic: "update_dispatch_task",
callback: function(data, envelope) {
}
});
回调函数中,data是发布者发送的数据,是对数据的包装,包含以下类容:
- **消息的元数据,类似:频道(channel)、主题(topic)
** - **时间戳和其他可能已经存在的数据
** - **由发送者添加的数据
**
3.publish(channel, topic,data, callback)
触发已经订阅的事件
channel:用以识别触发哪个channel
topic:用以识别频道上的哪个topic
data:传递到subscribe回调函数的参数
callback:触发事件后的回调函数
postal.publish({
channel: "dispatch",
topic: "update_dispatch_task",
data: {
name: ""
}
});
4.unsubscribe(handler)
注销(取消订阅)事件
handler:subscribe的返回值,传入注销对应的事件
subscription.unsubscribe()