Home  >  Article  >  Web Front-end  >  How to implement two-way binding in js

How to implement two-way binding in js

亚连
亚连Original
2018-06-14 10:36:392220browse

Below I will share with you an explanation of the simplest two-way binding example in js. It has a good reference value and I hope it will be helpful to everyone.

Copy the code and put it into the page to run and see the effect

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<input type="text" id="myinput" >
<script>
  function watch(obj,key,callback) {
    var old = obj[key];
    Object.defineProperty(obj,key,{
      set:function(val){
        var oldVal = old;
        old = val;
        callback(val,oldVal,this);
      },
      get:function(){
        return old;
      }
    });
  }
  var input = document.getElementById("myinput");
  var obj = {};
  watch(obj, "input",function (val) {
    input.value = val;
    console.log("这里是不管view层,还是module层修改后的回调,最后设置的值是"+val);
  });
  input.onkeyup = function () {
    obj.input = input.value;
  };
</script>
</body>
</html>

Code test

If you modify the value in the input, you will see the new value printed out on the console

Modify the value of obj.input on the console, the value in the input box will also change accordingly, and the event will also be triggered. , Get new value

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to implement the input search function using JS

How to use the node module and npm package management tool

How to implement a guessing game using JavaScript (detailed tutorial)

How to implement various sorting methods using js

How to use cdn optimization in vue

How to judge the file type size in js

How to judge the file type size in js

How to implement the drop-down box fuzzy query function in Angular

Security knowledge about crypto modules in Nodejs (detailed tutorial)

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

Statement:
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