• es6的set和get实现数据双向绑定,监听变量变化。


    直接上代码吧,这个用法真的是效仿了.net的枚举。

    vue的数据双向绑定就是用这个实现的。

    代码:

      

    html:
        <input type="text" id="input1">
        <input type="text" id="input2">
        我每次比input1的值加1=>
        <span id="span"></span>
    
    js:
    var oInput1 = document.getElementById('input1');
        var oInput2 = document.getElementById('input2');
        var oSpan = document.getElementById('span');
        var obj = {};
        Object.defineProperties(obj, {
            val1: {
                configurable: true,
                get: function() {
                    oInput1.value = 0;
                    oInput2.value = 0;
                    oSpan.innerHTML = 0;
                    return 0
                },
                set: function(newValue) {
                    oInput2.value = newValue;
                    oSpan.innerHTML = Number(newValue) ? Number(newValue) : 0
                }
            },
            val2: {
                configurable: true,
                get: function() {
                    oInput1.value = 0;
                    oInput2.value = 0;
                    oSpan.innerHTML = 0;
                    return 0
                },
                set: function(newValue) {
                    oInput1.value = newValue;
                    oSpan.innerHTML = Number(newValue)+1;
                }
            }
        })
        oInput1.value = obj.val1;
        oInput1.addEventListener('keyup', function() {
            obj.val1 = oInput1.value;
        }, false);
        oInput2.addEventListener('keyup', function() {
            obj.val2 = oInput2.value;
        }, false);
    

      

    监听变量值变化,数据双向绑定:

      

    html:
        <button onclick="plus()">  +  </button>
        <p id="p">0</p>
    js:
        function plus() {
            watchVal.val = ++watchVal.value;
            var screen = document.getElementById('p');
            var text='00';
            text=watchVal.value;
            screen.innerHTML = text;
            console.log(watchVal.value)
        }
        var watchVal = {
            value: 0,
            get val() {
                console.log('取值', this.value);
                return this.value;
            },
            set val(vals) {
                this.value = vals;
                console.log('存过后的值', this.value);
            }
        }
    

      

    【未完待续,后续我封装一个自己的插件哦~】

  • 相关阅读:
    DelphiXE
    Delphi_检查exe文件是否是"随机基址"
    Delphi_按字节比较两个文件
    HTTP 头部
    NumberFormat usage
    tomcat 配置
    android 与JS之间的交互
    离线安装SDK
    Android SDK更新 Connection to http://dl-ssl.google.com refused
    自定义圆形图片
  • 原文地址:https://www.cnblogs.com/webSong/p/8301443.html
Copyright © 2020-2023  润新知