Knockout event binding for input keypress causes weird behavior

China☆狼群 提交于 2019-12-07 03:45:51

问题


Long story short, I want to enable users to hit enter on an input element and certain method in my viewmodel be called. Here is my html input:

<input id="searchBox" class="input-xxlarge" type="text" data-bind="value: searchText, valueUpdate: 'afterkeydown', event: { keypress: $parent.searchKeyboardCmd}">

and here is my method in vm:

searchKeyboardCmd = function (data, event) { if (event.keyCode == 13) searchCmd(); };

everything works fine and searchCmd is called when I hit enter on input, but the problem is that I can type nothing in input, i.e. everything I type into input is ignored. Thank you in advance for your help.


回答1:


According to KO docs you have to return true from your event handler if you want the default action proceed.

searchKeyboardCmd = function (data, event) {
    if (event.keyCode == 13) searchCmd();
    return true;
};



回答2:


here's a fiddle which demonstrates what ur trying to do and also replace event 'keypress' in ur code with keyup and remove $parent with only the function name unless the textfield is inside a knockout foreach loop..here is the below modified code

<input id="searchBox" class="input-xxlarge" type="text" data-bind="value: searchText, valueUpdate: 'afterkeydown', event: { keyup: searchKeyboardCmd}"



回答3:


Here is a working sample.

http://jsfiddle.net/tlarson/qG6yv/

<!-- ko with: stuff -->
  <input id="searchBox" class="input-xxlarge" type="text" 
    data-bind="value: searchText, valueUpdate: 'afterkeydown', 
    event: { keypress: $parent.searchKeyboardCmd}">   
<!-- /ko -->

And the javascript:

var stuffvm = function(){
    var self = this;

    self.searchText = ko.observable();
};

var vm = function() {
    var self = this;

    self.stuff = new stuffvm();

    self.searchCmd = function() {
        console.log("search triggered");
    };

    self.searchKeyboardCmd = function (data, event) { 
        if (event.keyCode == 13) {
            self.searchCmd(); 
        }
        return true;
    }
}

ko.applyBindings(new vm());


来源:https://stackoverflow.com/questions/16120356/knockout-event-binding-for-input-keypress-causes-weird-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!