键入时通过节流(或速率限制)验证文本输入

Validate text input with throttling (or rateLimit'ing) while typing

因为我认为相当微不足道的事情,我陷入了困境。目标是在用户输入时通过限制来验证用户输入。

根据我读过的内容,我需要使用 purecomputed observable 并用 rateLimit 扩展它。或者像这样:

this.validateSmsValue = ko.pureComputed(function() {
        let hasPlaceholder = self.smsMsg().indexOf('[link_placeholder]');
        self.smsMsgIsValid(hasPlaceholder !== undefined);
    })
     .extend({
       rateLimit: { method: "notifyWhenChangesStop", timeout: 500 }
     });

在 HTML 中,我正在尝试绑定:

<input id="smsMsgEdit"type="text" data-bind="textInput: smsMsg, event: {keypress: validateSmsValue}" maxlength="160" >

在当前形式中,我收到错误 Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.

我正在继续阅读文档并搜索示例,但我的 Google-fu 失败了。

KnockoutJS 在用户停止输入 1/2 秒后验证文本字段输入的正确方法是什么?

我认为您正在寻找的是对可观察对象的订阅,而不是使用计算函数。也不需要单独的按键事件绑定。

function viewModel(){
  var self = this;
  
  self.myValue = ko.observable().extend({ rateLimit: { timeout: 500, method: "notifyWhenChangesStop" } });
  
  //validate
  self.myValue.subscribe(function(newValue){
    console.log(!isNaN(newValue));
  });
  
}

ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

Value is a number?
<input type="text" data-bind="textInput: myValue" />