TIL icon indicating copy to clipboard operation
TIL copied to clipboard

没事写了个双向绑定(defineProperty&&Proxy)

Open xiaohesong opened this issue 6 years ago • 0 comments

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>测试</title>
</head>
<body>
  Name: <input class='input' name='input'/>
  add: <button class='button'>+</button>
</body>
<script>
let input = document.querySelector('.input')
let button = document.querySelector('.button')
let num = 0

button.addEventListener('click', function(){
  num++
  input.value = num
})

let proxy = new Proxy(input, {
  set(trapTarget, key, value, receiver) {
    if (isNaN(value)) {
      throw new TypeError("Property must be a number.");
    }

    return Reflect.set(trapTarget, key, value, receiver);
  }
})

Object.defineProperty(input, 'value', {
  enumerable: true,
  value: '',
  get: function () {
    console.log('get this value is', this._value)
    return this._value
  },
  set: function (val) {
    console.log('set this value is', val)
    this._value = val
  }
})


</script>
</html>

xiaohesong avatar Dec 04 '18 09:12 xiaohesong