Open MJingv opened 4 years ago
class Event {
constructor () {
this._events = new Map()
this._maxListeners = 10
}
on (name, fn) {
let handler = this._events.get(name) || []
this._events.set(name, [...handler, fn])
return this
}
emit (name, ...args) {
let handler = this._events.get(name)
if (!handler || !handler.length) return null
for (let i in handler) {
handler[i](args)
}
return this
}
off (name, fn) {
let handler = this._events.get(name)
if (!handler) return
let res = handler.filter(i => i.toString() !== fn.toString())
this._events.set(name, res)
return this
}
once (name, fn) {
let handler = this._events.get(name)
if (!handler) return
for (let i in handler) {
this.off(name, handler[i])
}
this.on(name, fn)
return this
}
}
let e = new Event()
e.on('change', (name) => {console.log('!!!' + name)}).on('change', (name) => {console.log('~~~' + name)})
e.emit('change', 'jehol')