原生js双向数据绑定 前端数据劫持Object.defineProperty

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="dadasdasda">
    //obj.hello为变量
<div id="bbbbb">{{ obj.hello }}</div>

<script type="text/javascript">

var obj={};

//前端数据劫持 对象属性的监听
Object.defineProperty(obj,'hello',{
set:function(val){
console.log("val: ");
console.log(val);
document.getElementById("bbbbb").innerHTML=val;

}
})

document.getElementById("dadasdasda").onkeyup=function (e) {
console.log(e.target.value);

obj.hello=e.target.value;
console.log("obj.hello: "+obj.hello);
}
obj.hello = "";
</script>
</body>
</html>
posted @ 2018-08-27 21:59  haveProgress  阅读(262)  评论(0编辑  收藏  举报