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
|
const bucket = new WeakMap()
let activeEffect = null
function effect(fn) { if (typeof fn !== 'function') return; activeEffect = fn fn() activeEffect = null }
function track(target, key) { if (!activeEffect) return let depMap = bucket.get(target) if (!depMap) { depMap = new Map() bucket.set(target, depMap) } let depSet = depMap.get(key) if (!depSet) { depSet = new Set() bucket.get(target).set(key, depSet) } depSet.add(activeEffect) }
function trigger(target, key) { bucket.get(target).get(key).forEach(fn => fn()) }
function reactive(obj) { if (typeof obj !== 'object' || obj === null) return; return new Proxy(obj, { get(target, key) { track(target, key) return target[key] }, set(target, key, value) { target[key] = value trigger(target, key) return true } }) }
|