作者: 文章来源:
本文原地址:https://www.mimiwuqi.com/biji/194983.html

class EventEmitter {
constructor() {
this.events = {};
}
on(name, handler){
this.events[name] = this.events[name] || [];
this.events[name].push(handler);
}
emit(name, ...args) {
if (!this.events[name]) throw new Error('该事件未注册');
this.events[name].forEach(fn => fn.call(this, ...args));
}
off(name, handler) {
if (!this.events[name]) throw new Error('该事件未注册');
if (!handler) {
delete this.events[name];
} else {
this.events[name] = this.events[name].filter(fn => fn !== handler);
}
}
once(name, handler) {
funlction fn(...args) {
handler.call(this, ...args);
this.off(name, fn);
}
this.on(name, fn);
}
}更多 建站笔记 请访问 https://www.mimiwuqi.com/biji/