-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathb-target-iterator.js
More file actions
45 lines (37 loc) · 895 Bytes
/
b-target-iterator.js
File metadata and controls
45 lines (37 loc) · 895 Bytes
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
'use strict';
class TargetIterator {
#target = null;
constructor(target) {
this.#target = target;
}
[Symbol.asyncIterator]() {
const next = () => new Promise((resolve) => {
const listener = (event) => {
this.#target.removeEventListener('step', listener);
resolve({
value: event.detail,
done: false,
});
};
this.#target.addEventListener('step', listener);
});
const iterator = { next };
return iterator;
}
}
// Usage
const main = async () => {
const target = new EventTarget();
const iterator = new TargetIterator(target);
let counter = 0;
setInterval(() => {
counter++;
const data = { detail: { counter } };
const event = new CustomEvent('step', data);
target.dispatchEvent(event);
}, 1000);
for await (const step of iterator) {
console.log(step);
}
};
main();