class EventEmitter {
constructor() {
this.events = {}
}
//实现(注册)订阅
on(type, callBack) {
!this.events[type]?this.events[type] = [callBack]:this.events[type].push(callBack)
}
//删除订阅
off(type, callBack){
if(!this.events[type]) return;
this.events[type] = this.events[type],filter(item=>{
return item !== callBack;
})
}
//只执行一次订阅事件(订阅完成,触发一次后,立即执行删除订阅)
once(type,callBack){
function fn(){
callBack();
this.off(type,fn)
}
this.on(type,fn)
}
//触发事件
emit(type,...rest){
this.events[type] && this.events[type].forEach((fn)=>{
fn.apply(this,rest)
})
}
}
//使用方法:
const event = new EventEmitter();
const handle = (...rest) => {
console.log(rest);
};
//如果不订阅,直接触发
event.emit("click", 1, 2, 3, 4); // undefined
//先订阅,后出发
event.on("click", handle);
event.emit("click", 1, 2, 3, 4); //[1,2,3,4]
//删除订阅,再触发
event.off("click", handle);
event.emit("click", 1, 2); // undefined
//只订阅一次
event.once('myClick', ()=>{
console.log(11111)
})
event.emit("myClick"); // 11111
event.emit("myClick"); // undefined
手写发布订阅代码
最新推荐文章于 2024-07-17 15:26:15 发布