Create Custom KnockoutJS Binding For Enter Key Press

Today I had to add an event to an input box that when the user hits enter on the keyboard, it would call a JavaScript function. However, it’s pretty easy to do with a onkeypress=”” but it still uses a lot of other JavaScript and jQuery. I wanted to do this with using a custom KnockoutJS binding for the enter key so lets take a look at the mark up first.

//Field for typing. enterKey is the name of the custom binding.
<input id="name" data-bind="value: name, enterKey: addName" /> 

//This is the button for if they click instead of enter.
<input id="addName" type="button" data-bind="click: addName" value="Add" /> 

Take notice that in the first line and in the second like they are both pointing to the same function addName. Now lets take a look at the custom binding called enterKey.

// Custom Binding
ko.bindingHandlers.enterKey = {
  init: function (element, valueAccessor, allBindings, data, context) {
    var wrapper = function (data, event) {
      if (event.keyCode === 13) {
        valueAccessor().call(this, data, event);
      }
    };
    ko.applyBindingsToNode(element, { event: { keyup: wrapper } }, context);
  }
};

The cool thing about this customer knockoutjs binding is that you could pass it any function to call. All you would have to do in the markup is data-bind="enterKey: aDifferentFunction" and it would work the same. This obviously works great if you have multiple instances where you would like to check the enter key press and do a certain function without having to do a ton of checking of what’s calling what.

This was answered by Dennis on StackOverflow when I asked how to convert javascript onkeypress to knockoutjs to call on enter.

Leave a Reply

Your email address will not be published. Required fields are marked *

StackOverflow Profile