javascript - 将前置和后置事件触发器添加到 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
解决方案
推荐阅读
- php - 如何从表css中的2个字段json获取数据
- rsync - Rsync:如果校验和相同,则保持目标文件不变
- java - Android:通知不生成默认声音
- arraylist - Flutter:语音到文本
- android - 什么是 android.enableD8=false 的替代品,因为它已被弃用
- javascript - Javascript IE 11 MouseEvent 细节替代
- laravel - Laravel 5.5 css 路径在公共目录下不起作用
- java - Java用问号标记解析XML?
- c# - 在 Unity 中使用多线程生成对象
- sql - 即使条件不存在也如何显示行