发布订阅模式

//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)
}
}

 

posted @ 2019-04-05 18:15  那个村  阅读(254)  评论(0编辑  收藏  举报