发布订阅模式
Posted coderzx
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了发布订阅模式相关的知识,希望对你有一定的参考价值。
//node事件模块
function Event () {
this.cacheEvent = {}
}
Event.prototype.on = function (type, handle) {
if (!this.cacheEvent[type]){
this.cacheEvent[type] = [handle]
} else {
this.cacheEvent[type].push(handle)
}
}
Event.prototype.emmit = function () {
const type = arguments[0]
const arg = Array.prototype.slice.call(arguments, 1)
if (this.cacheEvent[type]) {
for(let i = 0; i < this.cacheEvent[type].length; i++){
this.cacheEvent[type][i](...arg)
if (this.cacheEvent[type][i].flag){
this.cacheEvent[type].splice(i,1)
}
}
}
}
Event.prototype.remove = function (type, handle) {
this.cacheEvent[type] = this.cacheEvent[type].filter(item => {
return item !== handle
})
}
Event.prototype.empty = function (type) {
this.cacheEvent[type] = []
}
Event.prototype.once = function (type, handle) {
handle.flag = true
if (!this.cacheEvent[type]){
this.cacheEvent[type] = [handle]
} else {
this.cacheEvent[type].push(handle)
}
}
以上是关于发布订阅模式的主要内容,如果未能解决你的问题,请参考以下文章