-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReactivityJs.js
75 lines (64 loc) · 1.8 KB
/
ReactivityJs.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
export class ReactivityJs {
handlers = new Set();
proxy;
static bind(target, ...handlers) {
const observer = new this(...handlers);
observer.proxy = new Proxy(target, observer.proxyHandlers());
return observer.proxy;
}
constructor(...handlers) {
if (handlers.length > 0) {
this.setControlFunctions(handlers[handlers.length - 1]);
this.watch(...handlers);
}
}
watch(...handlers) {
handlers.forEach(handler => {
if (typeof handler === 'function') {
this.handlers.add(handler);
}
});
}
unwatch(...handlers) {
handlers.forEach(handler => {
this.handlers.delete(handler);
});
}
stopWatch() {
this.handlers = new Set();
}
setControlFunctions(controller) {
if (controller == null) {
return;
}
if (typeof controller === 'object' && Array.isArray(controller) === false) {
controller.watch = this.watch.bind(this);
controller.unwatch = this.unwatch.bind(this);
controller.stopWatch = this.stopWatch.bind(this);
}
}
proxyHandlers() {
return {
get: this.get.bind(this),
set: this.set.bind(this),
deleteProperty: this.delete.bind(this)
};
}
get(target, prop) {
return Reflect.get(...arguments);
}
set(target, prop, value) {
return this.notify(Reflect.set(...arguments));
}
delete(target, prop) {
return this.notify(Reflect.deleteProperty(...arguments));
}
notify(isUpdated) {
if (isUpdated) {
this.handlers.forEach(handler => {
handler(this.proxy);
});
}
return isUpdated;
}
}