首页 > 解决方案 > 将前置和后置事件触发器添加到 Pub-Sub 模式

问题描述

我正在使用 PubSub 实现,并认为有一个发布事件选项会很好。当我在做这件事的时候,我们也不妨先做一个。我希望语法类似于

events.subscribe.pre(event, callback)
events.subscribe(event, callback)
events.subscribe.post(event, callback)
events.publish(event, args) <-- args are optional

我找不到太多关于“subscribe()”和“subscribe.pre()”是否可能都是有效选项的信息。过了很长一段时间,我最终用原型来解决这个问题,并将第二层方法绑定到原型。

有用。有没有更好的方法来做到这一点,可能是作为一个班级,总体来说这只是一个坏主意吗?

function PubSub() {}

PubSub.prototype = {
    subscribers: {
        pre: {},
        main: {},
        post: {}
    }
}

PubSub.prototype.subscribe = function(event,callback) {
  this.subscribers.main[event] = this.subscribers.main[event] || [];
  this.subscribers.main[event].push(callback);
}

PubSub.prototype.subscribe.pre = function(event,callback) {
    this.subscribers.pre[event] = this.subscribers.pre[event] || [];
    this.subscribers.pre[event].push(callback);
    
}.bind(PubSub.prototype)

PubSub.prototype.subscribe.post = function(event,callback) {
    this.subscribers.post[event] = this.subscribers.post[event] || [];
    this.subscribers.post[event].push(callback);
}.bind(PubSub.prototype)

PubSub.prototype.publish = function(...params) {
  const keys = ['pre', 'main', 'post']
    for (const k of keys){
    const [event, ...args] = params
    if (this.subscribers[k][event]) {
      const subs = this.subscribers[k][event]
      for (const sub of subs) {
          sub(...args)
      }
    }
  }
}


x = new PubSub();

x.subscribe.post("test", () => {console.log('test post')})
x.subscribe("test", () => {console.log('test sub')})
x.subscribe.pre("test", () => {console.log('test pre')})

x.publish("test") // Triggers pre -> main -> post as expected
x.publish("ing") // Nothing happens because there are no subscribers

标签: javascript

解决方案


推荐阅读