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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…