JavaScript 香草双向绑定

JavaScript Vanilla Two Way Binding

我发现这个非常简短但方便的双向绑定代码是用纯 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);
})();

如果想要的结果是取第一个输入值,用它做点什么,把它放到第二个输入上那么为什么这么认真?

(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);
})();

另一种在 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 对此非常有用 - 特别是当您查看浏览器对此的支持时。