1class EventEmitter {
2 constructor() {
3 this.events = {};
4 }
5 on(name, fn) {
6 if (!this.events[name]) {
7 this.events[name] = [];
8 }
9 this.events[name].push(fn);
10 return this;
11 }
12 emit(name, ...args) {
13 if (!this.events[name]) {
14 console.log("没有注册这个事件");
15 return this;
16 }
17 this.events[name].forEach((fn) => fn.apply(this, args));
18 return this;
19 }
20 once(name, fn) {
21
22 const func = (...args) => {
23 this.off(name, func);
24 fn.apply(this, args);
25 };
26 this.on(name, func);
27 return this;
28 }
29 off(name, fn) {
30 if (!this.events[name]) {
31 return this;
32 }
33
34 if (!fn) {
35 delete this.events[name];
36 return this;
37 }
38
39 const index = this.evnets[name].indexOf(fn);
40 this.evnets[name].splice(index, 1);
41 return this;
42 }
43}
1const eventEmitter = new EventEmitter();
2eventEmitter.on("test", (args) => {
3 console.log(args);
4});
5eventEmitter.emit("test", { a: 1 });