This article mainly shares with you the js simple two-way binding case code. Just copy the code into the page and run it to see the effect. I hope it can help everyone.
<span style="font-size: 14px;"><!DOCTYPE html><html lang="en"><head><br/> <meta charset="UTF-8"><br/> <title>Title</title></head><body><input type="text" id="myinput" ><script><br/> function watch(obj,key,callback) {<br/> var old = obj[key]; Object.defineProperty(obj,key,{<br/> set:function(val){<br/> var oldVal = old;<br/> old = val;<br/> callback(val,oldVal,this);<br/> },<br/> get:function(){<br/> return old;<br/> }<br/> });<br/> } var input = document.getElementById("myinput"); var obj = {};<br/> watch(obj, "input",function (val) {<br/> input.value = val;<br/> console.log("这里是不管view层,还是module层修改后的回调,最后设置的值是"+val);<br/> });<br/><br/> input.onkeyup = function () {<br/> obj.input = input.value;<br/> };</script></body></html><br/></span>
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 in the console, the value in the input box will also change accordingly, and the event will be triggered to obtain the new value
Related recommendations:
Sharing about three methods of realizing two-way data binding in JavaScript
Easy implementation of two-way binding of javascript data_javascript skills
In-depth understanding of the implementation principle of vue.js two-way binding
The above is the detailed content of js simple two-way binding case code. For more information, please follow other related articles on the PHP Chinese website!