寫一個eventEmitter類,包括on()、off()、once()、emit()方法
1、on(event,fn):監聽event事件,事件觸發時呼叫fn函式;
2、once(event,fn):為指定事件註冊一個單次監聽器,單次監聽器最多隻觸發一次,觸發後立即解除監聽器;
3、emit(event,arg1,arg2,arg3...):觸發event事件,並把引數arg1,arg2,arg3....傳給事件處理函式;
4、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
}}