2 Star 0 Fork 0

huying5/reactCode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
event-bus.js 1.30 KB
一键复制 编辑 原始数据 按行查看 历史
huying5 提交于 2021-08-17 23:11 . event-bus
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);
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/hycodeWork/react-code.git
git@gitee.com:hycodeWork/react-code.git
hycodeWork
react-code
reactCode
master

搜索帮助