UNPKG

wft-utils

Version:

The commonly used tool functions in daily development

83 lines (72 loc) 1.59 kB
class Dep { constructor() { this.subscribers = new Set() } depend () { if (activeEffect) { this.subscribers.add(activeEffect) } } notify () { this.subscribers.forEach(effect => { effect() }) } } let activeEffect = null function watchEffect (effect) { activeEffect = effect effect() activeEffect = null } const targetMap = new WeakMap() function getDep (target, key) { let depsMap = targetMap.get(target) if (!depsMap) { depsMap = new Map() targetMap.set(target, depsMap) } let dep = depsMap.get(key) if (!dep) { dep = new Dep() depsMap.set(key, dep) } return dep } function reactive (raw) { return new Proxy(raw, { get (target, key) { const dep = getDep(target, key) dep.depend() return target[key] }, set (target, key, newValue) { if(newValue !== target[key]) { const dep = getDep(target, key) target[key] = newValue dep.notify() } } }) } // 测试代码 let info = reactive({ count: 100, name: 'WFT_INFO' }) let foo = reactive({ name: 'WFT_FOO' }) watchEffect(function () { console.log(info.count * 2 + info.name, 'info----->>>') }) watchEffect(function () { console.log(info.count ** 2, 'info---->>') }) watchEffect(function () { console.log(foo.name, 'foo---->>>') }) setTimeout(() => { info.count++ setTimeout(() => { info.name = '哈哈哈' setTimeout(() => { foo.name = '呵呵呵' }, 2000) }, 2000) }, 2000)