We’ve covered storage properties (rethinking javascript objects (I) — objects and their properties) and how to define a storage property with Object.defineProperty(), Today we show how to implement two-way data binding using Object.defineProperty().

A memory property has four property descriptors: Get, set, 64x, enumerable. Let’s review how to create a storage property:

var user = {
    name: ' '
}
Object.defineProperty(user, 'nickname', {
    configurable: true,
    enumerable: true,
    get: function() {
        return this.name
    },
    set: function(value) {
        this.name = value
    }
})
Copy the code

We created a storage property called nickname for user.

Next we rewrite get and set to bind them to the DOM and implement bidirectional data binding.

<input type="text" id="foo">

<script>
    var user = {}
    Object.defineProperty(user, 'inputValue', {
        configurable: true,
        get: function() {
            return document.getElementById('foo').value
        },
        set: function(value) {
            document.getElementById('foo').value = value
        }
    })
</script>
Copy the code

If we open the console and change the value of user.inputValue, we’ll see that the value in the input field also changes. Also, if we enter a value in the input field and print user.inputValue on the console, we’ll see that user.inputValue has changed as well. So we have two-way data binding.

If more than one DOM is bound to the same data, we can listen for the keyUP event of the input field. Once the keyUP event is triggered, we assign the value of user.inputValue to another DOM.

<input type="text" id="foo">
<p id="test"></p>

<script>
    var user = {}
    Object.defineProperty(user, 'inputValue', {
        configurable: true,
        get: function() {
            return document.getElementById('foo').value
        },
        set: function(value) {
            document.getElementById('foo').value = value
            document.getElementById('test').innerHTML = value
        }
    })
    document.getElementById('foo').addEventListener('keyup'.function() {
        document.getElementById('test').innerHTML = user.inputValue
    })
Copy the code

Finally, attach the source code picture

Object.defineproperty () does not have to be used to implement two-way data binding. It uses get and set of memory attributes. The following code also implements two-way data binding:

<input type="text" id="foo">
<p id="test"></p>

<script>
    var user = {
      get inputValue() { 
        return document.getElementById('foo').value
      },
      set inputValue(value) {
        document.getElementById('foo').value = value
        document.getElementById('test').innerHTML = value
      }
    }
    document.getElementById('foo').addEventListener('keyup'.function() {
      document.getElementById('test').innerHTML = user.inputValue
    })
</script>
Copy the code