如何在同一个输入元素中绑定值和keydown事件?

时间:2017-06-28 15:55:11

标签: javascript knockout.js

当我将Observable变量绑定到input值和keydown事件时,它不会更新可观察值



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>
&#13;
&#13;
&#13;

如何在同一输入元素中绑定valueevent: {keydown: myKeyDown}

1 个答案:

答案 0 :(得分:2)

您可以在事件监听器中返回true,以确保按键关闭使其进入输入。

但是,您可能希望查看textInput绑定(textInput: value)并订阅value而不是......

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>