let index = 1;
function debounce(func, wait) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
const creatEventHub = () => ({
hub: Object.create(null),//{a:[事件,事件]}
on(eventName, handeler) {//订阅,注册
if (!this.hub[eventName]) {
this.hub[eventName] = [];
}
this.hub[eventName].push(handeler);
},
emit(eventName, data) {//发布,执行
if (this.hub[eventName]) {
this.hub[eventName].forEach((handeler) => handeler(data));
}
},
off(event,handler){
const index=this.hub[event].findIndex(h=>h===handler);
if(index>-1){
this.hub[event].splice(index,1)
}
}
});
window.creatEventHub = creatEventHub();
window.creatEventHub.on("onInfoUpdate", (res) => {
console.log(res,'====');
});
document.getElementById("btn").addEventListener("click", debounce(()=>{
window.creatEventHub.emit("onInfoUpdate", { a: index });
index++;
},1000));