接触到Angulr.js和Vue.js后,提到最多的就是双向绑定
下面将用JavaScript实现数据的双向绑定
<!DOCTYPE html> <html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="text" id="foo" value="as"/>
</body>
<script type="text/javascript">
function bindModelInput(obj, property, domElem) {
Object.defineProperty(obj, property, {
get: function() {
return domElem.value;
},
set: function(newValue) {
debugger;
domElem.value = newValue;
},
configurable: true
});
}
user = {};
var inputElem = document.getElementById("foo");
bindModelInput(user,'name',inputElem);
debugger;
user.name = "Joe";
alert("input value is now "+inputElem.value) //input元素现在的值是'Joe'
inputElem.value = 'Bob';
alert("user.name is now "+user.name) //现在model中的value是Bob
</script>
</html>