-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatch.ts
34 lines (32 loc) · 791 Bytes
/
watch.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
import { effect } from "./effect";
function traverse(value:any, seen = new Set()){
if (typeof value !== 'object' || value === null || seen.has(value)) return
seen.add(value)
for (const k in value) {
traverse(value[k],seen)
}
return value
}
export function watch(source:any,cb:any){
let getter:any
if (typeof source == 'function'){
getter=source
}else{
getter = ()=>traverse(source)
}
let oldValue:any,newValue:any
const effectFn = effect(
()=>{
return getter()
},
{
lazy:true,
scheduler() {
newValue = effectFn()
cb(newValue,oldValue)
oldValue = newValue
}
}
)
oldValue = effectFn()
}