function Event() {
this.events = {}
}
Event.prototype.on = function(key, fn) {
if (!this.events) {
this.events = {}
}
this.events[key] = this.events[key] || []
this.events[key].push(fn)
}
Event.prototype.emit = function(key, ...args) {
let fns = this.events[key] || []
fns.forEach(fn => {
fn(...args)
});
}
Event.prototype.off = function(key, cb) {
let fns = this.events[key] || []
if (fns.length) {
this.events[key] = fns.filter(fn=>fn !== cb && fn.l !== cb)
}
}
Event.prototype.once = function(key, cb) {
let once = (...args) => {
cb(...args)
this.off(key, once)
}
once.l = cb
this.on(key, once)
}
let parent = new Event()
let fn1 = (...args) => {
console.log(1, ...args)
}
let fn2 = (...args) => {
console.log(2, ...args)
}
parent.once('action', fn1)
parent.once('action', fn2)
parent.emit('action', 11, 22)
parent.emit('action', 11, 22)