pub-sub也就是發(fā)布訂閱的模式是我們比較常用的設(shè)計模式,它一種一對多的依賴關(guān)系,在收到相應(yīng)的消息之后會更新訂閱該消息的所有事件。今天在寫項目時候正好用到了,就寫了一個簡版的。
class PubSub {
constructor() {
this.handlers = {}
}
// 訂閱
on(key, handler) {
if (!(key in this.handlers)) {
this.handlers[key] = []
}
this.handlers[key].push(handler)
}
// 卸載
off(key, handler) {
const index = this.handlers[key].findIndex(item => {
item === handler
})
// 不存在直接返回
if (index < 0) {
return
}
if (this.handlers[key].length === 1) {
// 只有一個直接刪除key 節(jié)省內(nèi)存
delete this.handlers[key]
} else {
this.handlers[key].splice(index, 1)
}
}
// 觸發(fā)
walk(key) {
// 取出參數(shù)并轉(zhuǎn)化為數(shù)組
const args = Array.prototype.slice.call(arguments, 1)
this.handlers[key].forEach(handler => {
// 防止this指向亂掉
handler.apply(this, args)
});
}
}
測試
const pubSub = new PubSub()
fn1 = function(val1, val2) {
console.log(val1, val2) // hah hahah
}
fn2 = function(val1) {
console.log(val1) // hah
}
pubSub.on('ms1', fn1)
pubSub.on('ms1', fn2)
pubSub.walk('ms1', 'hah', 'hahah')