zoukankan      html  css  js  c++  java
  • 原生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>
  • 相关阅读:
    Python for i 循环
    Python 输入分数并评
    用户名和密码的输入
    cocos2d-x 3.0学习
    VS2008 ShotKey
    Cocos2d-x 3.0的安装方法
    VFC
    一、在WIN7 64位系统平台,VS2013环境下安装WTL90_4090_RC1(2014-04-01)
    http://www.vcf-online.org/
    Win7 64位 VS2012 安装 Qt5
  • 原文地址:https://www.cnblogs.com/gxp69/p/7073415.html
Copyright © 2011-2022 走看看