在VanillaJS中模拟模型双向数据绑定

Emulating ng-model two way data binding in VanillaJS

本文关键字:数据绑定 模型 模拟 VanillaJS      更新时间:2023-09-26

我习惯于使用AngularJS框架,在使用VanillaJS时遇到了一个障碍,看起来很简单,但当我上网时,我只发现了过时的做法。

首先,我需要能够基本上拥有一个<textarea>元素,并将其更改立即传播到JS到HTML。例如(在JS psuedocode中):

 <textarea id="#editor" when-changed="foo(newValue)"></textarea>
 <p id="#parsedEditor"></p>
 function foo(newValue) {
     document.getElementByID("#parsedEditor") = bar(newValue);
 }
 function bar(text) {
     return text.replace(" ", "x");
  }         

我想要的是,每当textarea的值发生变化时,它都会通过一些过滤器,然后呈现到前端。

在这种情况下,每当#editor的值发生变化时,它的新值就会被发送到回调函数foo,并使用bar过滤器对其进行解析,#parsedEditor就会用新值更新。在AngularJS中,它基本上是(忽略确切的语法和最佳实践):

 <textarea ng-model="text"></textarea>
 <p ng-bind-html="parsedText"></p>
 function controller($scope) {
     $scope.$watch('text', function(newValue, oldValue) {
          $scope.parsedText = newValue.replace(" ", "x");
     }
 }

我在网上搜索了实现这一点的方法,发现Object.observe()只是一种新提出的方法,而.watch()在MDN上不推荐使用。此外,onchange属性仅在取消选择textarea元素后调用回调函数,并且我希望在值更改时传播它,而不是在取消选择时传播它。

我觉得在JS中一定有一种更简单的方法可以做到这一点,但我错过了?

以下是基于我上面评论的工作代码:

<textarea id="#editor" oninput="foo(event.currentTarget.value)"></textarea>
<p id="#parsedEditor"></p>

我假设你的意图是用x替换所有空格。如果是这样,你可能想要一个正则表达式:

function foo(newValue) {
   document.getElementById("#parsedEditor").innerText = bar(newValue);
}
function bar(text) {
   return text.replace(/'s/gi, "x");
}  

您需要在所有目标浏览器中进行测试,并记住HTML5 API在IE9中并不总是如预期那样工作:http://caniuse.com/#search=input

Fiddle在这里:https://jsfiddle.net/mcgraphix/71evt900/