-
Notifications
You must be signed in to change notification settings - Fork 2
/
event.ts
50 lines (41 loc) · 1.28 KB
/
event.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
import React from "react";
export interface IEvent {
[l: string]: any
}
export type IEventCallback = (a: IEvent) => any
export type IEventEmiterStorage = {
[l: string]: Array<IEventCallback>
}
export type IEventEmiter = {
_events: IEventEmiterStorage,
dispatch: (eventType: string, data: IEvent) => void,
subscribe: (eventType: string, data: IEvent) => number,
unsubscribe: (eventType: string, idx: number) => void,
}
export default class EventEmitter extends React.Component {
private _events: IEventEmiterStorage = {};
constructor(props?: any) {
super(props);
}
public dispatch(eventType: string, data: IEvent) {
if (!this._events[eventType]) return;
for (const callback of this._events[eventType]) {
callback(data);
}
}
public subscribe(id: string, callback: (data: IEvent) => any) {
if (!this._events[id]) {
this._events[id] = [];
}
const idx = this._events[id].length;
this._events[id].push(callback);
return idx;
}
public unsubscribe(id: string, idx: number) {
if (!this._events[id]) return;
this._events[id].splice(idx, 1);
if (this._events[id].length === 0) {
delete this._events[id];
}
}
}