发布 --- 订阅
const obj = {
// 保存所有的订阅者
list: {},
// 添加订阅者
addList(key, callback) {
const { list } = this
if (!list[key]) {
list[key] = []
}
list[key].push(callback)
},
// 发布者
publish(key, opt) {
const arr = this.list[key]
arr.forEach((element) => {
element(opt)
})
},
}
obj.addList('m200', (opt) => {
console.log('小花', opt)
})
obj.addList('m200', (opt) => {
console.log('小白', opt)
})
obj.addList('m40', (opt) => {
console.log('小红', opt)
})
obj.publish('m200', '1000万')
obj.publish('m40', '200万')
网友评论