JS achieve two-way data binding

Reference herein https://www.cnblogs.com/tianhaining/p/8425345.html

First, start with a face questions of Kazakhstan, is v-model vue is how to achieve a two-way data binding
Keke, began to recite the classic face questions following the
data first, when I was new instance when a vue, which was declared in the data and it is preserved in the form of getter and setter, triggering a method is Object.defineProperty. This method There are two methods set and get. save data. When the data changes, setter will be notified to watch, so data-driven changes in view of ~ (Of course, this is not an absolute right, only their own summary)

Then this Object.defineProperty This method is doing it.

It defines an object directly on a new attribute, or modify existing properties of an object and return the object.

This method allows precise to add or modify the properties of an object. Ordinary operations by assigning attributes to add are enumerable, can be presented during the property enumerated (for ... in or Object.keys method), the value of these attributes can be changed, it can be deleted. This method allows additional options to modify the default (or configuration). By default, use Object.defineProperty () to add the attribute value can not be modified.

var obj = {}; 
    Object.defineProperty (obj, 'Test' , { 
        GET: () => {the console.log ( 'GET is called a' )}, 
        SET: () => {the console.log ( 'SET is called a ' )} 
    })

In the browser controller when I was assigned to the object, call the function set, when I read the value of the object when calling the get function.

See here for two-way data binding or a series of vue face MVVM design pattern also, or vue of the biggest advantages and other questions have a deeper understanding.

Back then he said with a native JS achieve two-way data binding
code is as follows

<input type="text" id="input_1">
<span id="span_1"></span>


<script>
    var obj = {};
    Object.defineProperty(obj, 'test', {
        set: (newVal)=>{
            document.getElementById('input_1').value = newVal;
            document.getElementById('span_1').innerHTML = newVal;
        }
    });
    document.addEventListener('keyup', (e)=>{
        obj.test = e.target.value;      //事件监听
    })

</script>

At this point I can achieve what I enter into the input box on the page synchronized to the span tag, and the console will be assigned to obj.test synchronized to the input and span tags.

Guess you like

Origin www.cnblogs.com/JiAyInNnNn/p/11460814.html