发布订阅模式的代码实现
let fabuObj={
saveData:{},
on(type,cb){
if (!this.saveData[type]) {
this.saveData[type]=[]
}
this.saveData[type].push(cb)
},
emit(type,...canshu){
if (!this.saveData[type].length) {
console.log("无人订阅 无需通知");
}else{
console.log( this.saveData[type].length);
this.saveData[type].forEach(element => {
element.apply(this,[...canshu])
});
}
}
}
let baozipu=Object.create(fabuObj)
baozipu.on("三鲜包子",function (params) {
console.log("小明订购了三鲜包子还有"+params);
})
baozipu.on("三鲜包子",function (params) {
console.log("小久久订购了三鲜包子还有"+params);
})
baozipu.on("三鲜包子",function (params) {
console.log("小轻轻订购了三鲜包子还有"+params);
})
baozipu.emit("三鲜包子",20)