-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProxyObserver.js
93 lines (75 loc) · 2.38 KB
/
ProxyObserver.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
curl https://raw.githubusercontent.com/voischev/tool/main/ProxyObserver.js > ProxyObserver.js
const po = new ProxyObserver((entries) => {
entries.forEach(({ value, prop, target }) => {
console.log(value, prop, target);
});
});
const user = po.observe({ name: 'Ivan' });
user.age = '34';
*/
class ProxyObserver {
#observationTargets = [];
#queuedEntries = [];
#callback = null;
constructor(callback) {
if (typeof callback !== 'function') {
throw new Error('callback must be a function');
}
this.#callback = callback;
}
observe(target) {
const isTargetAlreadyObserved = this.#observationTargets.some(item => item === target);
if (isTargetAlreadyObserved) {
return;
}
const isObject = (target && (typeof target === 'object' || typeof target === 'function'));
if (!isObject) {
throw new Error('target must be an Object');
return;
}
this.#observationTargets.push(target);
let flag = false;
const handler = (target, prop, value) => {
const result = Reflect.set(target, prop, value);
if (typeof result === 'function') {
result.bind(target);
}
if (result) {
this.#queuedEntries.push({
prop,
value,
target,
});
if (!flag) {
flag = true;
requestAnimationFrame(() => {
flag = false;
if (this.#queuedEntries.length) {
this.#callback(this.takeRecords(), this);
}
});
}
}
return result;
}
const proxy = new Proxy(target, { set: handler });
if (this.#queuedEntries.length) {
this.#callback(this.takeRecords(), this);
}
return proxy;
}
unobserve(target) {
this.#observationTargets = this.#observationTargets.filter(item => item !== target);
}
disconnect() {
this.#observationTargets = [];
this.#queuedEntries = [];
this.#callback = null;
}
takeRecords() {
const records = this.#queuedEntries.slice();
this.#queuedEntries = [];
return records;
}
}