在knockoutjs上绑定keypress事件,可观察到没有填充 [英] Binding keypress event on knockoutjs, observable not populated
问题描述
需要一些关于knockoutjs和绑定按键事件的帮助。我正试图连接淘汰赛,以便我从文本框中选择回车键。所以我可以执行与单击按钮相同的操作。这有点难以解释,但希望这个JsFiddle将展示我想要实现的目标。
Need a little help with knockoutjs and binding a keypress event. I'm trying to hook up knockout so that I pick up on the enter keypress from within a text box. So I can perform the same action as clicking a button. Its a little tricky to explain but hopefully this JsFiddle will demonstrate what I'm trying to achieve.
我遇到的问题是可观察值不是得到更新,我认为它与一个observable有关,直到焦点离开文本框才会被更新?
The problem I have is that observable value is not getting updated and I think its something to do with an observable not being updated until focus moves away from the textbox?
这个问题的任何解决方案。
Any solutions to this problem.
谢谢!
推荐答案
一种选择是使用 valueUpdate
额外绑定以强制每个按键更新。例如,你会这样做:
One option is to use the valueUpdate
additional binding to force an update on each keypress. For example, you would do:
<input type="text" data-bind="value: InputValue, valueUpdate: 'afterkeydown', event: { keypress: RunSomethingKey }" />
如果那不是你想要的,那么你真的想要激活元素的变化事件你的经纪人。例如,使用jQuery,您可以执行以下操作: $(event.target).change();
。
If that is not what you are after, then really you would want to fire the element's change event in your handler. For example with jQuery, you would do something like: $(event.target).change();
.
将它移到自定义绑定中会更好。也许类似的事情(可能应该检查valueAccessor()的结果是否是函数):
It would be better though to move this into a custom binding. Maybe something like (probably should check if the result of valueAccessor() is a function):
ko.bindingHandlers.enterKey = {
init: function(element, valueAccessor, allBindings, vm) {
ko.utils.registerEventHandler(element, "keyup", function(event) {
if (event.keyCode === 13) {
ko.utils.triggerEvent(element, "change");
valueAccessor().call(vm, vm); //set "this" to the data and also pass it as first arg, in case function has "this" bound
}
return true;
});
}
};
以下是您更新的示例: http://jsfiddle.net/rniemeyer/nbnML/9/
Here is your sample updated: http://jsfiddle.net/rniemeyer/nbnML/9/
这篇关于在knockoutjs上绑定keypress事件,可观察到没有填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!