YvetteLau / Step-By-Step

不积跬步,无以至千里;
704 stars 66 forks source link

如何使用Proxy实现简单MVVM #44

Open zxza opened 5 years ago

Sonirjodxpro commented 5 years ago
<body>
  <div class="box">
    <div class="a"></div>
    <div class="b"></div>

    <input type="text" id="text" oninput="ffff();">

    <div class="c" id="tt"></div>
  </div>
</body>
<script>

  function fid(id) {
    return document.getElementById(`${id}`);
  }

  function ffff() {
    proo.text = fid('text').value;
  }
  let proo = new Proxy({ text: '' }, {
    get(target, key, receiver) {
      if (key in target) {
        return target[key];
      } else {
        return new ReferenceError('emmmm');
      }
    },
    set(target, key, value, receiver) {
      target[key] = value;
      fid('tt').innerText = value;
      if (fid('text').value !== value) {
        fid('text').value = value;
      }
    }
  })
</script>

不知道我的这个算不算。。。。。

Liruimin2 commented 5 years ago
 let onWatch =(obj,setBind,getLogger)=>{
    let handler ={
      get(target,property,receiver){
        getLogger(target,property);
        return Reflect.get(target,property,receiver)
      },
      set(target,property,value,receiver){
        setBind(value,property);
        return Reflect.set(target,property,value)
      }
    }
    return new Proxy(obj,handler)
  }
  let obj={a:1}
  let p=onWatch(
    obj,
    (v,property)=>{
      // console.log(${property},${v});

    },
    (target,property)=>{
      console.log('`${property}`=${target[property]}');

    }
  )