JavaScript Vanilla双向绑定

时间:2018-06-30 06:52:37

标签: javascript javascript-databinding

我发现这是用纯JavaScript编写的非常简短但方便的两种方式的绑定代码。数据绑定工作正常,但是我想要从第一个输入中获取值并将其乘以所需的数字,然后将结果绑定到下一个输入中。我将不胜感激。 这是我的HTML代码:

<input class="age" type="number">
<input class="age" type="number">

和JavaScript代码:

    var $scope = {};
(function () {
    var bindClasses = ["age"];
    var attachEvent = function (classNames) {
        classNames.forEach(function (className) {
            var elements = document.getElementsByClassName(className);
            for (var index in elements) {
                elements[index].onkeyup = function () {
                    for (var index in elements) {
                        elements[index].value = this.value;
                    }
                }
            }
            Object.defineProperty($scope, className, {
                set: function (newValue) {
                    for (var index in elements) {
                        elements[index].value = newValue;
                    }
                }
            });
        });
    };
    attachEvent(bindClasses);
})();

2 个答案:

答案 0 :(得分:0)

如果期望的结果是第一个输入值,则对其进行处理,然后将其输入第二个输入,那为什么这么严重?

(function () {
  var bindClasses = ["age"];
  var attachEvent = function (classNames) {
    classNames.forEach( function( className ) {
      var els = document.getElementsByClassName( className ),
          from, to;
      if ( 2 > els.length ) {
        return;
      }
      from = els[0];
      to   = els[els.length - 1];

      from.addEventListener( 'keyup', function() {
        var v = this.value;
        // Do whatever you want with that value
        // Then assign it to last el
        if ( isNaN( v ) ) {
          return;
        }
        v = v / 2;
        to.value = v;
      });
    });
  };
  attachEvent(bindClasses);
})();

答案 1 :(得分:0)

在JS中进行双向绑定的另一种简单方法可能是这样的:

<!-- index.html -->
<form action="#" onsubmit="vm.onSubmit(event, this)">
    <input onchange="vm.username=this.value" type="text" id="Username">
    <input type="submit" id="Submit">
</form>
<script src="vm.js"></script>


// vm.js - vanialla JS
let vm = {
    _username: "",
    get username() {
        return this._username;
    },
    set username(value) {
        this._username = value;
    },
    onSubmit: function (event, element) {
        console.log(this.username);
    }
}

JS Getters和Setters对此非常好-特别是当您查看浏览器对此的支持时。