Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
935 views
in Technique[技术] by (71.8m points)

knockout.js - Call a function on enter key press

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

ko.bindingHandlers.enterkey = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
    var inputSelector = 'input,textarea,select';
    $(document).on('keypress', inputSelector, function (e) {
        var allBindings = allBindingsAccessor();
        $(element).on('keypress', 'input, textarea, select', function (e) {
            var keyCode = e.which || e.keyCode;
            if (keyCode !== 13) {
                alert('a');
                return true;
            }

            var target = e.target;
            target.blur();

            allBindings.enterkey.call(viewModel, viewModel, target, element);
            alert('b');
            return false;
        });
    });
}
};
ko.applyBindings(viewModel);

HTML

<input type="text" data-bind="value:sendMessageText, enterkey: sendMessage" /> 

ViewModel

function contactsModel(){
    var self = this;
    self.jid=ko.observable();
    self.userName=ko.observable();
    self.sendMsgText=ko.observable();
    self.sendMessage = function(){
        if(self.sendMessageText() == '' )
            alert("Enter something in input field");
        else{
            var message = {
                to : self.userName(),
                message : self.sendMsgText()
            }
            self.sentMessages.push(message);
            sendMessage(message);
        }

     }
 }

Any idea's about what is wrong here or suggestions for better approach.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No need for a custom binding, just use knockout's keypress event(Knockout docs):

<input type="text"
       data-bind="textInput : keyword, 
                  event: {keypress: onEnter}" >
</input>

And your function:

that.onEnter = function(d,e){
    e.keyCode === 13 && that.search();  
    return true;
};

JSFiddle example

EDIT: New binding from knockout(3.2.0) : textInput - obviates the need to have a valueUpdate binding.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...