代码拉取完成,页面将自动刷新
class EventEmitter {
_infinty = 2;
constructor(maxListeners) {
this.events = {};
this.maxListeners = maxListeners || this._infinty;
}
emit(event, ...args) {
const cbs = this.events[event];
if (!cbs) {
console.log("没有这个事件");
return this;
}
cbs.forEach((cb) => cb.apply(this, args));
return this;
}
on(event, cb) {
if (!this.events[event]) {
this.events[event] = [];
}
//TODO 拦截最大监听
if(this.maxListeners !== this._infinty && this.events[event].length >= this.maxListeners){
console.warn(`当前事件${event}超过最大监听数`)
return this
}
this.events[event].push(cb);
return this;
}
once(event, cb) {
const func = (...args) => {
this.off(event, func);
cb.apply(this.args);
};
this.on(event, func);
return this;
}
off(event, cb) {
if (!cb) {
this.events[event] = null;
} else {
this.events[event] = this.events[event].filter((item) => item !== cb);
}
return this;
}
}
const add = (a, b) => console.log(a + b);
const log = (...args) => console.log(...args);
const even = new EventEmitter();
even.on("add", add);
even.on("log", log);
even.emit("add", 1, 2);
even.emit("log", "he huy");
even.off("add");
even.once("once", add);
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。