- 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._events={}
}
on(event,callback){
let callbacks = this._events[event] || []
this._events[event] = callbacks.push(callback);
return this
}
off(event,callback){
let callbacks = this._events[event]
this._events[event] = callbacks && callbacks.filter(function(fn){
return fn !== callback;
})
return this
}
emit(eventName,...args) {
const callbacks = this._events[eventName]
callbacks.map(cb => {
cb(...args)
})
return this;
}
once(event,callback){
let wrap = (...args) => {
callback.apply(this, args)
this.off(event, wrap)
}
this.on(event, wrap )
return this
}
}
网友评论