generated from homebridge/homebridge-plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleListener.ts
45 lines (39 loc) · 1.08 KB
/
SimpleListener.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
type ListenerRemover = () => boolean;
type ListenerAction = (...args: Array<unknown>) => void;
// This class let's to add functions that are fire method is called.
//
export class SimpleListener {
private listeners: Array<ListenerAction> = [ ];
public getSize = (): number => {
return this.listeners.length;
};
public add = (action: ListenerAction): ListenerRemover => {
this.listeners.push(action);
let removed = false;
return (): boolean => {
if (removed) {
return false;
}
removed = true;
return this.remove(action);
};
};
public remove = (action: ListenerAction): boolean => {
for (let i = 0; i < this.listeners.length; ++i) {
if (action === this.listeners[i]) {
this.listeners.splice(i, 1);
return true;
}
}
return false;
};
public fire = (...args: Array<unknown>): void => {
for (let i = 0; i < this.listeners.length; ++i) {
const listener = this.listeners[i];
listener.apply(listener, args);
}
};
public clean = (): void => {
this.listeners = [ ];
};
}