class Event {
constructor () {
this.handlers = {}
}
// on
addEventListener(type,handler) {
if(!(type in this.handlers)) {
this.handlers[type] = []
}
if(!handler) {
throw `请添加${type}事件`
}
this.handlers[type].push(handler) ;
return this;
}
// emit
dispatchEvent(type,...params) {
if(!(type in this.handlers)){
throw new Error('事件未注册')
}
this.handlers[type].forEach(handler =>{
handler(...params)
})
return this;
}
// off
removeEventListener(type,handler){
if(!(type in this.handlers)){
throw new Error('事件未注册')
}
if(!handler){
delete this.handlers[type]
}else {
const idx = this.handlers[type].findIndex(ele => ele === handler)
if(idx === -1) {
throw new Error('无该绑定事件')
}
this.handlers[type].splice(idx,1) ;
if(this.handlers[type].length === 0){
delete this.handlers[type]
}
}
}
}
const evn = new Event() ;
const l1 = ()=>{ console.log('l1');}
evn.addEventListener('load',l1)
evn.addEventListener('load',(msg)=>{
console.log(msg);
})
evn.addEventListener('load',()=>{
console.log('addEvent33333333Listener');
})
evn.dispatchEvent('load','emit').addEventListener('load2',()=>{
console.log('load2');
}).dispatchEvent('load2','emit') ;