@zoodogood/utils 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
class CustomCollector {
|
|
2
|
+
#callback;
|
|
3
|
+
|
|
4
|
+
constructor({target, event, filter, time = 0}){
|
|
5
|
+
if ("on" in target === false){
|
|
6
|
+
throw new Error("Target must be similar to EventEmitter.prototype — target haven't method 'on'");
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
this.target = target;
|
|
10
|
+
this.event = event;
|
|
11
|
+
this.filter = filter;
|
|
12
|
+
this.time = time;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
setCallback(callback){
|
|
16
|
+
|
|
17
|
+
const handler = (...params) => {
|
|
18
|
+
const passed = this?.filter(params);
|
|
19
|
+
|
|
20
|
+
if (!!passed === true){
|
|
21
|
+
callback.apply(this, params);
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
this.handle(handler);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
handle(){
|
|
29
|
+
this.end();
|
|
30
|
+
|
|
31
|
+
this.#callback = handler;
|
|
32
|
+
this.target.on(this.event, this.#callback);
|
|
33
|
+
|
|
34
|
+
if (this.time > 0){
|
|
35
|
+
this.setTimeout(this.time);
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
end(){
|
|
40
|
+
this.removeTimeout();
|
|
41
|
+
this.target.removeListener(this.event, this.#callback);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
removeTimeout(){
|
|
45
|
+
clearTimeout(this.timeoutId);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
setTimeout(ms){
|
|
49
|
+
const callback = this.end.bind(this);
|
|
50
|
+
this.timeoutId = setTimeout(callback, ms);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export { CustomCollector };
|