简体   繁体   中英

How to bind value and keydown event in same input element?

When I binding an Observable variable to an input value, and keydown event as well, it's not updating the observable value

 function vModel() { var vm = this; vm.value = ko.observable(); vm.keyDown = function() { }; } ko.applyBindings(new vModel()); 
  <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <input type="text" data-bind="value: value, event: {keydown: keyDown}"> <span data-bind="text: value"></span> 

How can I bind value and event: {keydown: myKeyDown} in same input element?

You can return true in your event listener to make sure the key down makes it to the input.

However , you might want to look at the textInput binding ( textInput: value ) and subscribe to value instead...

 function vModel() { var vm = this; vm.value = ko.observable(); vm.keyDown = function() { console.log("key down"); return true; }; } ko.applyBindings(new vModel()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <input type="text" data-bind="value: value, event: {keydown: keyDown}"> <span data-bind="text: value"></span> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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