forked from sajibcse68/MyDailyLearn
-
Notifications
You must be signed in to change notification settings - Fork 1
/
js-reactivity-visuality.js
54 lines (45 loc) · 932 Bytes
/
js-reactivity-visuality.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
let data = { price: 5, quantity: 2 };
let target, total, salePrice;
class Dep {
constructor() {
this.subscribers = [];
}
depend() {
if (target && !this.subscribers.includes(target)) {
this.subscribers.push(target);
}
}
notify() {
this.subscribers.forEach(sub => sub());
}
}
Object.keys(data).forEach(key => {
let internalValue = data[key];
const dep = new Dep();
Object.defineProperty(data, key, {
get() {
dep.depend();
return internalValue;
},
set(newVal) {
internalValue = newVal;
dep.notify();
}
});
});
function watcher(myFunc) {
target = myFunc;
target();
target = null;
}
watcher(() => {
total = data.price * data.quantity;
});
watcher(() => {
salePrice = data.price * 0.9;
});
// total; // 10
// salePrice; // 4.5
// data.price = 12; // updating price
// total; // 24
// salePrice; // 10.8