实现 Eventemitter 类,有on、emit、off 方法
- on(event,fn):监听event事件,事件触发时调用fn函数;
- once(event,fn):为指定事件注册一个单次监听器,单次监听器最多只触发一次,触发后立即解除监听器;
- emit(event,arg1,arg2,arg3...):触发event事件,并把参数arg1,arg2,arg3....传给事件处理函数;
- off(event,fn):停止监听某个事件
class EventEmitter{
constructor(){
this._envents = {}
}
on(event,callback){ //监听event事件,触发时调用callback函数
let callbacks = this._events[event] || []
callbacks.push(callback)
this._events[event] = callbacks
return this
}
off(event,callback){ //停止监听event事件
let callbacks = this._events[event]
this._events[event] = callbacks && callbacks.filter(fn => fn !== callback)
return this
}
emit(...args){ //触发事件,并把参数传给事件的处理函数
const event = args[0]
const params = [].slice.call(args,1)
const callbacks = this._events[event]
callbacks.forEach(fn => fn.apply(this.params))
return this
}
once(event,callback){ //为事件注册单次监听器
let wrapFanc = (...args) => {
callback.apply(this.args)
this.off(event,wrapFanc)
}
this.on(event,wrapFanc)
return this
}
}