MVVM核心实现代码(简易实现)

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>MVVM</title>
 6 </head>
 7 <body>
 8     <input id="user.name" type="text" > 姓名
 9     <input id="user.age" type="text" > 年龄
10     <script type="text/javascript">
11         function User(){
12             var user = this;
13             var u_name = document.getElementById('user.name');
14             var u_age = document.getElementById('user.age');
15             u_name.addEventListener('change', function(){ user.name = this.value; });
16             u_age.addEventListener('change', function(){ user.age = this.value;  });
17             Object.defineProperties(user,{
18                 name : {
19                     get : function(){ return name; },
20                     set : function(new_name){ name = new_name; u_name.value = name; }
21                 },
22                 age : {
23                     get : function(){ return age; },
24                     set : function(new_age){ age = new_age; u_age.value = age; }
25                 }
26             });
27             return user;
28         };
29         var user = new User();
30         user.name = '覆水难收';
31     </script>
32 </body>
33 </html>

 

posted @ 2016-10-26 17:47  登高一呼  阅读(618)  评论(0编辑  收藏  举报