class MyEvent {
fnMap = {}
constructor(){
}
addEvent(key,fn){
if(!(key in this.fnMap)){
this.fnMap[key] = []
}
this.fnMap[key].push(fn)
}
dispatchEvent(key,...arg){
if(!(key in this.fnMap)){
console.error(key,"事件未注册")
return;
}
this.fnMap[key].forEach(fn => {
fn(...arg);
});
}
removeEvent(key){
if(!(key in this.fnMap)){
console.error(key,"事件未注册")
return;
}
delete this.fnMap[key]
}
}
let test = new MyEvent();
test.addEvent("callFn", (param) => {
console.log("回调1",param)
})
test.addEvent("callFn", (param) => {
console.log("回调2",param)
})
test.dispatchEvent("callFn","参数1");
test.dispatchEvent("callFn","参数2");
dom 中观察者的应用
document.body.addEventListener('click' , ()=> {
console.log("点击处理1")
})
document.body.addEventListener('click' , ()=> {
console.log("点击处理2")
})