-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
81 lines (62 loc) · 2.01 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
export interface IEventHandlers {
[key: string]: Map<Function, boolean>;
}
export default class EventManagment {
private eventHandlersMap: IEventHandlers = {
'*': new Map(),
};
private isDebug: boolean = false;
private addEventHandler(eventName: string, callback: Function, isOnce: boolean = false) {
if (!this.eventHandlersMap[eventName]) {
this.eventHandlersMap[eventName] = new Map();
}
if (callback && !this.eventHandlersMap[eventName].has(callback)) {
this.eventHandlersMap[eventName].set(callback, isOnce);
}
}
private callHandlers(eventName: string, payload: any, realEventName?: string) {
if (this.eventHandlersMap[eventName]) {
this.eventHandlersMap[eventName].forEach((isOnce: boolean, handler: Function) => {
handler && handler(payload, { eventName: realEventName || eventName, isOnce });
if (isOnce) {
this.off(eventName, handler);
}
});
}
}
public setDebug(isDebug: boolean) {
this.isDebug = isDebug;
return this;
}
public on(eventName: string, callback: Function): EventManagment {
this.addEventHandler(eventName, callback);
return this;
}
public once(eventName: string, callback: Function): EventManagment {
this.addEventHandler(eventName, callback, true);
return this;
}
public off(eventName: string, callback: Function): EventManagment {
if (!this.eventHandlersMap[eventName]) {
return this;
}
if (callback && this.eventHandlersMap[eventName].has(callback)) {
this.eventHandlersMap[eventName].delete(callback);
}
return this;
}
public emit(eventName: string, payload?: any): void {
if (this.isDebug) {
console.info(`[${this.constructor.name}]: Fires ${eventName}`);
}
this.callHandlers('*', payload, eventName);
this.callHandlers(eventName, payload);
}
/// Aliases:
public fire = this.emit;
public listen = this.on;
public subscribe = this.on;
public remove = this.off;
public unsubscribe = this.off;
///
}