//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)
}
}
转载于:https://www.cnblogs.com/CoderZX/p/10659380.html