Skip to content

Commit 84ce57a

Browse files
committed
feat: support multiple subscribe for the same event
1 parent e40c364 commit 84ce57a

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/common/event.ts

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
export class EventEmitter {
2+
private _events = new Map<string, Function[]>();
3+
4+
public emit<ArgsType = any>(name: string, args: ArgsType) {
5+
const events = this._events.get(name);
6+
if (events && events.length > 0) {
7+
// The log for development
8+
console.log('event emit:', name, args);
9+
events.forEach((callEvent) => {
10+
callEvent(args);
11+
});
12+
}
13+
}
14+
15+
public subscribe<T = any>(name: string | string[], callback: Function ) {
16+
if (Array.isArray(name)) {
17+
name.forEach((key: string) => {
18+
this.assignEvent(key, callback);
19+
});
20+
} else {
21+
this.assignEvent(name, callback);
22+
}
23+
// The log for development
24+
console.log('event on:', name);
25+
}
26+
27+
public assignEvent<T>(name: string, callback: Function) {
28+
const event = this._events.get(name);
29+
if (event) {
30+
event.push(callback);
31+
} else {
32+
this._events.set(name, [callback] );
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)