Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
xiaohesong opened this issue Dec 4, 2018 · 0 comments
Open

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

xiaohesong opened this issue Dec 4, 2018 · 0 comments
Labels
example 一些例子

Comments

@xiaohesong
Copy link
Owner

<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 xiaohesong added the example 一些例子 label Dec 11, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
example 一些例子
Projects
None yet
Development

No branches or pull requests

1 participant