手写发布订阅
class pubSub {
constructor(){
this.list = {}
}
subscribe(key, fn) {
if (!this.list[key]) {
this.list[key] = []
}
this.list[key].push(fn)
}
publish(key, ...args) {
for (let fn of this.list[key]) {
fn.apply(this, args)
}
}
unSubscribe(key, fn) {
let fnlist = this.list[key]
if (!fnlist) return
if (!fn) {
fnlist.length = 0
} else {
fnlist.forEach((item, index) => {
if (item === index) {
fnlist.splice(index, 1)
}
})
}
}
}
let p1 = new pubSub()
p1.subscribe('onwork', (time) => { console.log("上班了:" + time) })
p1.subscribe('offwork', (time) => { console.log("下班了:" + time) })
p1.subscribe('launch', (time) => { console.log("吃饭了:" + time) })
p1.publish('onwork', '9:00:00')
p1.publish('offwork', '18:00:00')
p1.publish('launch', '12:00:00')
p1.unSubscribe('onwork')
p1.publish('onwork', '1222:00:00')