javascript PubSub / EventBus / Mediator JavaScript模式

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript PubSub / EventBus / Mediator JavaScript模式相关的知识,希望对你有一定的参考价值。

function EventBus (){
  this.events = []
}
EventBus.prototype.trigger = function(name, data) {
  this.events.map(item => item.name == name && item.callback(data))
  return this
}
EventBus.prototype.on = function(name, callback) {
  this.events.push({name: name, callback: callback})
  return this
}
EventBus.prototype.off = function(name) {
  this.events = this.events.filter(item => item.name !== name)
  return this
}

//Usage Example

const events = new EventBus()

events
  .on("myEvent", function(data){
    console.log(data.peanuts, data.oranges)
  })
  .on("anotherEvent", function(data){
    console.log(data.jelly, data.butter)
  })

events
  .trigger("myEvent",{peanuts: "peanuts", oranges: "oranges"})
  .off("myEvent")
  .trigger("anotherEvent", {jelly: "jelly", butter: "buttsss"})
  .off("anotherEvent")

以上是关于javascript PubSub / EventBus / Mediator JavaScript模式的主要内容,如果未能解决你的问题,请参考以下文章

每个用户的 GCP PubSub(或 GCP 任务)同步处理

javascript PubSub / EventBus / Mediator JavaScript模式

JavaScript 中 PubSub / 过多事件和事件处理程序的性能成本?

javascript 活动PubSub

javascript pubsub - 缓存obj

javascript PubSub活动