-
Notifications
You must be signed in to change notification settings - Fork 0
/
jiggle.js
80 lines (72 loc) · 1.65 KB
/
jiggle.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
const depsMap = new Map()
let currentEffect = null
const effectsStack = []
function createEffect(fn) {
const effect = function effect(...args) {
if (effectsStack.indexOf(effect) === -1) {
try {
currentEffect = effect
effectsStack.push(effect)
return fn(...args)
} finally {
effectsStack.pop()
currentEffect = effectsStack[effectsStack.length - 1]
}
}
}
effect()
}
function render(element, content) {
const app = document.querySelector(element)
if (app !== null) {
app.innerHTML = content
}
}
function reactive(obj) {
const keys = Object.keys(obj)
const reactiveObj = {}
keys.forEach((key) => {
let value = obj[key]
Object.defineProperty(reactiveObj, key, {
get() {
console.log(`Getting value, ${value}`)
track(reactiveObj, key)
return value
},
set(newValue) {
console.log(`Setting value, ${newValue}`)
if (newValue !== value) {
value = newValue
trigger(reactiveObj, key)
}
}
})
})
return reactiveObj
}
function track(target, key) {
if (currentEffect) {
let deps = depsMap.get(target)
if (!deps) {
deps = new Map()
depsMap.set(target, deps)
}
dep = deps.get(key)
if (!dep) {
dep = new Set()
deps.set(key, dep)
}
dep.add(currentEffect)
}
}
function trigger(target, key) {
const deps = depsMap.get(target)
if (!deps) return;
const dep = deps.get(key)
if (dep) {
const effectsToRun = new Set(dep)
effectsToRun.forEach(effect => {
effect()
})
}
}