【发布时间】: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)