【问题标题】:Knockout JS - textInput binding update is delayed by one characterKnockout JS - textInput 绑定更新延迟一个字符
【发布时间】:2017-07-05 20:43:00
【问题描述】:

我目前正在尝试显示一条消息,该消息取决于使用 knockout.js 即时更新我的​​输入文本框的内容。 textInput 绑定似乎工作得很好,除了它只更新之后我已经输入了一个字符。在第一个字符上,它说它没有定义。

HTML:

 <input id="userResponse" 
                       data-bind="textInput: textInput,
                              hasFocus: responseSelected,
                              ojComponent: {component: 'ojInputText', 
                                            value: userResponse,
                                            rootAttributes: {
                                            style:'font-size:32px; max-width:100%;'}}"
                       autofocus/>

JS

self.textInput = ko.observable();
self.responseTypeValidation = function (keyCode) {
                oj.Logger.log("input: " +self.textInput());
                if (self.promptMetadata()) {

                    if(self.textInput().match(/[a-z]/))
                    {
                        self.responseErrorMessage("Numbers only");
                    }
                    else {
                       self.responseErrorMessage('');
                    }                      
                }
            };

例如,当我输入“hello”时,它会抛出错误,提示 textInput 在“h”上未定义,然后当我输入“ello”时,它会执行我真正想要它做的事情(即显示“仅数字”信息)。为什么它不会在第一个输入字符上更新?任何帮助解决这个问题将不胜感激

编辑: 这是输入框读取“he”时的日志,其中“h”抛出错误而“e”尚未被读取

jobCommand.js:81 Uncaught TypeError: Cannot read property 'match' of undefined
at jobCommandContentViewModel.self.responseTypeValidation (jobCommand.js:81)
at ControllerViewModel.keyDown (jobCommand.js:33)
at HTMLDivElement.<anonymous> (appController.js:60)
at HTMLDivElement.dispatch (jquery-3.1.1.js:5201)
at HTMLDivElement.elemData.handle (jquery-3.1.1.js:5009)


ojcore.js:262 input: h

【问题讨论】:

  • 听起来有时间问题 - 也许responseTypeValidation 在输入值实际可用于self.textInput() 之前触发?
  • 你怎么打电话给responseTypeValidation
  • 我也是这么想的,直到我尝试将它放入一个每次按下一个键时都会调用的函数中,第一个总是未定义的
  • @Michael Best responseTypeValidation 当前位于每次按下键时都会调用的函数中,并且该函数当前工作正常。调用是 self.responseTypeValidation(keyCode)

标签: javascript knockout.js


【解决方案1】:

由于使用 textInput,这会在每次击键或其他文本输入机制(例如剪切或拖动文本,不一定会引发任何焦点更改事件)时立即更新您的模型。

因此:

解决方案 1(计算):

self.Validation = ko.computed(function () {
    if(self.textInput().match(/[a-z]/))
        self.responseErrorMessage("Numbers only");
    else
        self.responseErrorMessage('');
}, self);

解决方案 2(订阅):

self.textInput.subscribe(function (newValue) {
    if(newValue.match(/[a-z]/))
        self.responseErrorMessage("Numbers only");
    else
        self.responseErrorMessage('');
});

【讨论】:

    猜你喜欢
    • 2018-10-19
    • 1970-01-01
    • 2021-03-06
    • 2021-06-15
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多