reactive

·  阅读 205

需求

写一个响应式系统实现

思路

1、proxy对数据进行劫持 2、在get时记录依赖,set时更新依赖

第一步

proxy劫持

const reactive = (raw) {
  get(target, key, receiver) {
    return Reflect.get(target, key, receiver);
  },
  set(target, key, value, receiver) {
    const result = Reflect.set(target, key, value, receiver);
    return result;
  },
}
复制代码

第二步

用一个weakMap记录所有的响应式对象,用一个订阅数组subscribes记录对应的依赖

//下班了,有空再写

const targetMap = new WeakMap()
let activeEffect
function createDep() {
  const subscribers = []
  function depend() {
    if (activeEffect) {
      subscribers.push(activeEffect)
    }
  }
  function notify() {
    subscribers.forEach(effect => {
      effect()
    })
  }
  return {
    depend,
    notify
  }
}

function initDep(target, key) {
  let depsMap = targetMap.get(target)
  if (!depsMap) {
    depsMap = new Map()
    targetMap.set(target, depsMap)
  }
  let dep = depsMap.get(key)
  if (!dep) {
    dep = createDep()
    depsMap.set(key, dep)
  }
  return dep
}
// 依赖跟踪
function track(target, key) {
  initDep(target, key).depend()
}

// 触发依赖
function trigger(target, key) {
  initDep(target, key).notify()
}

const reative = target => {
  return new Proxy(target, {
    get(target, key, receiver) {
      track(target, key)
      return Reflect.get(target, key, receiver)
    },
    set(target, key, value, receiver) {
      const result = Reflect.set(target, key, value, receiver)
      trigger(target, key)
      return result
    }
  })
}
复制代码
分类:
前端
标签:
收藏成功!
已添加到「」, 点击更改