-
Notifications
You must be signed in to change notification settings - Fork 2
/
on.ts
46 lines (33 loc) · 753 Bytes
/
on.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
function on(element: HTMLElement | Element, eventName: string) {
const stack = [];
const resolversFn = [];
const listener = (event) => {
if (resolversFn.length !== 0) {
while(resolversFn.length > 0) {
const fn = resolversFn.shift();
fn({ value: event, done: false });
}
return;
}
stack.push(Promise.resolve({ value: event, done: false }));
};
element.addEventListener(eventName, listener);
return {
[Symbol.asyncIterator]() {
return this;
},
next() {
if (stack.length !== 0) {
const pr = stack.shift();
return pr;
}
return new Promise((resolve) => {
resolversFn.push(resolve);
});
},
return() {
element.removeEventListener(eventName, listener);
}
};
};
export { on };