简体   繁体   English

跟踪输入文本框中的每个文本更改的 Knockout.js 事件

[英]knockout.js event that tracks every text change inside a input text box

I'm new to knockout js.我是淘汰赛的新手。 I want to call a function every time a text changes inside a text box.每次文本框中的文本更改时,我都想调用一个函数。 I researched a bit and implemented keyup , keydown and keypress but they didn't work properly.我研究了一下并实现了keyupkeydownkeypress但它们无法正常工作。 If anybody could give me a solution or please redirect me to some document that is helpful for my scenario.如果有人可以给我一个解决方案,或者请将我重定向到一些对我的场景有帮助的文档。 And If there is some sort of documentation about all of the events (inbuilt and custom) that are available in knockout Js, that would be really helpful.如果有关于淘汰赛 Js 中可用的所有事件(内置和自定义)的某种文档,那将非常有帮助。

To be specific about the problem:具体到这个问题:

  data-bind="value: targetProp, event:{keyup: $parent.changeProp}"

And in Js:在 Js 中:

    Inside parent:
     this.changeProp = function () {
                if (condition..) {
                       do something...
                }
            }
      

It's not working with key up.它不适用于钥匙。 For simple solution, please give me something that will alert the length of the string that has been written inside a textbox (on every text entered and deleted).对于简单的解决方案,请给我一些可以提醒文本框内写入的字符串长度的东西(在输入和删除的每个文本上)。

您可以使用valueUpdate: 'afterkeydown'它在用户开始输入字符后立即更新您的视图模型。

data-bind="value: targetProp, valueUpdate: 'afterkeydown'"

Or you can use textInput binding from the latest KO 3.2或者您可以使用最新 KO 3.2 中的textInput绑定

<input data-bind="textInput: userName" />

Apart from live updates, it correctly handles cut/paste, dragging, autocomplete.除了实时更新外,它还可以正确处理剪切/粘贴、拖动、自动完成。

You can also subscribe to the changes manually.您也可以手动订阅更改。

Make sure the targetProp is an observable, and when building the parent, subscribe manually to the changes :确保 targetProp 是一个可观察对象,并且在构建父对象时,手动订阅更改:

parent.targetProp = ko.observable(originalValue);

parent.targetProp.subscribe(function(newValue) {
    alert("The new value is " + newValue);
});

Edit: for an option binding:编辑:对于选项绑定:

<select data-bind="options: myObservableArray, value: selectedValue"></select>

in js:在js中:

self.selectedValue = ko.observable();

then:然后:

self.selectedValue.subscribe(function(newValue) {
    alert("The new value is " + newValue);
});

If you want to calculate in real time, as the person is typing, you can do this.如果你想实时计算,因为这个人正在打字,你可以这样做。

HTML HTML

<input type="text" id="description" class="form-control" maxlength="255" 
data-bind="value:description, event:{keyup:calcDescriptionCount}">
<br>
<span data-bind="text:descriptionCount"></span> charactors left.

ViewModel JS视图模型JS

self.description = ko.observable("");
self.descriptionCount = ko.observable(255);
self.calcDescriptionCount = function(){
    this.descriptionCount(255 - $("#description").val().length);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM