proxy响应式实现


DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Documenttitle>
  head>

  <body>
    <div class="inner1">div>
    <div class="inner2">div>
    <div>修改第一个name值<input type="text" class="input1" />div>
    <div>修改第二个name值<input type="text" class="input2" />div>
  body>
  <script>
    const inner1 = document.querySelector(".inner1");
    const inner2 = document.querySelector(".inner2");
    const input1 = document.querySelector(".input1");
    const input2 = document.querySelector(".input2");

    const proxy1 = reactive({
      name: "tsy",
    });
    const proxy2 = reactive({
      name: "nyx",
    });

    input1.onchange = function (e) {
      proxy1.name = e.target.value;
    };
    input2.onchange = function (e) {
      proxy2.name = e.target.value;
    };

    // const buckiet = new Map()
    const buckiet = new WeakMap();
    let effectFunction = null;

    function reactive(state) {
      return new Proxy(state, {
        get(target, key) {
          console.log("target=>", target);
          console.log(`获取了target的${key}属性`);
          track(target, key);
          return target[key];
        },
        set(target, key, value) {
          console.log("target=>", target);
          console.log(`修改了target的>${key}值为${value}`);
          target[key] = value;
          tigger(target, key);
        },
      });
    }

    /**
     * @description 在get时收集属性依赖:
     * @param {*} target 代理对象
     * @param {*} key 代理对象属性key
     * @return {*}
     */
    function track(target, key) {
      if (!effectFunction) return;
      let depMap = buckiet.get(target);
      if (!depMap) {
        depMap = new Map();
        buckiet.set(target, depMap);
      }
      let depSet = depMap.get(key);
      if (!depSet) {
        depSet = new Set();
        depMap.set(key, depSet);
      }
      depSet.add(effectFunction);
    }

    /**
     * @description: 在set触发,执行相关依赖
     * @param {*} target 代理对象
     * @param {*} key 触发修改的代理对象属性key
     * @return {*}
     */
    function tigger(target, key) {
      const depMap = buckiet.get(target);
      if (!depMap) return;
      const depSet = depMap.get(key);
      if (!depSet) return;
      depSet.forEach((fun) => fun());
    }

    /**
     * @description: 记录副作用函数
     * @param {*} fun 操作函数
     * @return {*}
     */
    function effect(fun) {
      if (typeof fun !== "function") return;
      effectFunction = fun;
      effectFunction();
      effectFunction = null;
    }

    // inner.innerHTML = proxy.name

    const handle1 = function () {
      inner1.innerHTML = proxy1.name;
    };
    const handle2 = function () {
      inner2.innerHTML = proxy2.name;
    };

    effect(handle1);
    effect(handle2);

    setTimeout(() => {
      proxy1.name = "糖糖";
    }, 1000);

    setTimeout(() => {
      proxy2.name = "abr";
    }, 2000);
  script>
html>

你可能感兴趣的:(JS实现,javascript,前端,开发语言,proxy模式)