gpt4 book ai didi

javascript - Knockout JS - textInput 绑定(bind)更新延迟一个字符

转载 作者:行者123 更新时间:2023-12-03 03:56:13 25 4
gpt4 key购买 nike

我目前正在尝试显示一条消息,该消息依赖于使用 knockout.js 对输入文本框内容进行即时更新。 textInput 绑定(bind)似乎工作得很好,只是它只在我已经输入一个字符之后更新。在第一个字符上,它表示它未定义。

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”时,它会抛出错误,指出“h”上的textInput未定义,然后当我输入“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

最佳答案

由于使用 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('');
});

关于javascript - Knockout JS - textInput 绑定(bind)更新延迟一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44935663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com