Home > Web Front-end > JS Tutorial > body text

How to implement two-way data binding in js

一个新手
Release: 2017-10-11 10:28:13
Original
2280 people have browsed it


Requirements

What do current frameworks emphasize on one-way binding and what are two-way binding?
- One-way data binding: It means that we write the template first, then integrate the template and data (the data may come from the background) to form HTML code, and then insert this HTML code into the document flow.
- Two-way data binding: Two-way binding between data model (Module) and view (View). That is, no matter whether I modify the relevant data of the data model or the data on the view, the corresponding data will be updated accordingly.

Implementation principle

The main thing is the binding of events.
- On the view layer (View), you can bind the keyup event to update the data model
- Use the Object.defineProperty() method on the data model to define the set method of the object. When the object property setting is triggered, Also modify the data in the view layer.

Case Code

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>Title</title></head><body><input type="text" id="myinput" ><script>
    var input = document.getElementById("myinput");    
    var obj = {};    
    Object.defineProperty(obj, "input", {
        get: function () {
            return input.value;
        },
        set: function (val) {
            input.value = val;
            changeCallback(input.value);
        }
    });

    input.onkeyup = function () {
        obj.input = input.value;
    };    function changeCallback(val) {
        console.log("这里是不管view层,还是module层修改后的回调,最后设置的值是"+val);
    }</script></body></html>
Copy after login

Ideas

  • First, we first use the Object.defineProperty() method to set the set method of obj, as long as we modify the input of obj Attribute, this set method will be triggered, and then the callback will be triggered, which realizes the data binding of the module layer.

  • Then, bind the keyup event on the input to realize the binding of the view layer.

  • As long as there is a modification between the two, regardless of the value of input or the input attribute of obj, the latest modified value will be obtained.

  • This should be the simplest idea.

The above is the detailed content of How to implement two-way data binding in js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template