手写一个发布订阅
Posted 冰love
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了手写一个发布订阅相关的知识,希望对你有一定的参考价值。
1:所有的发布订阅就是一个对象。

class Obersve {
event={} //等价于下面的constructor
// constructor() {
// this.event = {}
// }
subscribe(type, fn) { //订阅
if (Object.keys(this.event).includes(type)) {
this.event[type].push(fn)
} else {
this.event[type] = [fn]
}
}
publish(type, args = {}) { //发布
if (this.event[type]) {
this.event[type].map(item => {
item.call(this, { type,args})
})
}
}
}
const ober = new Obersve()
ober.subscribe(\'aaa\', function (e) {
console.log(`事件: ${e.type}`)
console.log(`消息: ${e.args.message}`)
})
ober.publish(\'aaa\', {
message: \'亮哥\'
})
以上是关于手写一个发布订阅的主要内容,如果未能解决你的问题,请参考以下文章