class MesNotify {
constructor() {
this.listeningList = [] // 监听列表
}
// 发布
publicListen(key, fn) {
(this.listeningList[key] || (this.listeningList[key] = [])).push(fn)
}
// 订阅
trigger() {
let triggerRef = Array.prototype.shift.call(arguments)
if (!this.listeningList[triggerRef] || this.listeningList[triggerRef].length === 0) {
return
}
let fns = this.listeningList[triggerRef]
for (let i = 0, fn; fn = fns[i]; i++) {
fn.apply(this, arguments)
}
}
// 移除
remove(key, fn) {
let fns = this.listeningList[key]
if (!fns) {
return false
}
if (!fn) {
fn && (fn.length = 0)
} else {
let fnIndex = fns.indexOf(fn)
fns.splice(fnIndex, 1)
return true
}
}
}
let emit = new MesNotify()
emit.publicListen(‘person‘, function (name, age) {
console.log(name, age)
})
emit.publicListen(‘animal‘, function (animal, hobby) {
console.log(animal, hobby)
})
emit.trigger(‘person‘, ‘张三‘, 19)
emit.trigger(‘animal‘, ‘袋鼠‘, ‘睡觉‘)
console.log(emit.remove(‘person‘, function (name, age) {
console.log(name, age)
})) // true
JS发布订阅者模式