Call a function on enter key press

后端 未结 5 1290
死守一世寂寞
死守一世寂寞 2020-12-14 14:46

How to call a function using knockout.js when enter key is pressed.. here is my code below.

ko.bindingHandlers.enterkey = {
init: function (element, valueAcc         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 15:09

    When you create your own knockout bindingHandler, it is used in the same way as the other bindingHanlders eg: data-bind="text: myvalue"

    so your HTML will need to look something like this

    An important binding to add is the valueUpdate: 'afterkeydown' binding. Without this binding when a user types text in the input and hits enter the onblur event is not raised prior to enterkey binding. This results in the observable returning an unexpected value and not the current text if the input's value is accessed in an action invoked by enterKey.

    Another Look at Custom Bindings for KnockoutJS

    EDIT
    This is what I have used previously on other projects. JsFiddle Demo

    ko.bindingHandlers.enterkey = {
        init: function (element, valueAccessor, allBindings, viewModel) {
            var callback = valueAccessor();
            $(element).keypress(function (event) {
                var keyCode = (event.which ? event.which : event.keyCode);
                if (keyCode === 13) {
                    callback.call(viewModel);
                    return false;
                }
                return true;
            });
        }
    };
    

提交回复
热议问题