原生js實現數據單向綁定


Object.defineProperty()方法直接在對象上定義一個新屬性,或修改對象上的現有屬性,並返回該對象。

Object.defineProperty(obj, prop, descriptor)

參數

  obj 定義屬性的對象。
  prop 要定義或修改的屬性的名稱。

  descriptor 定義或修改屬性的描述符。

  返回值 傳遞給函數的對象。
注意:數據描述符和訪問器描述符,不能同時存在(value,writable 和 get,set)

  get:函數return將被用作屬性的值。

  set:該函數將僅接收參數賦值給該屬性的新值。(在屬性改變時調用)

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8 <input type="text" id="aa"/>*<input type="text" id="cc"/>
 9 <span id="bb">{{hello}}</span>
10 
11 <script>
12    var obj = {};
13     Object.defineProperty(obj,'hello',{
14         enumerable: true,
15         configurable: true,
16         get: function() { return document.getElementById('aa').value; },
17         set:function(val){
18             document.getElementById('bb').innerHTML = val*obj.hello2;
19         }
20     });
21    Object.defineProperty(obj,'hello2',{
22        enumerable: true,
23        configurable: true,
24        get: function() { return document.getElementById('cc').value; },
25        set:function(val){
26            document.getElementById('bb').innerHTML = val*obj.hello;
27        }
28    });
29     document.getElementById('aa').onkeyup = function(){
30         obj.hello = this.value;
31     };
32    document.getElementById('cc').onkeyup = function(){
33        obj.hello2 = this.value;
34    };
35     obj.hello = "";
36     obj.hello2 = "";
37 </script>
38 
39 </body>
40 </html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM