Archive for June, 2012|Monthly archive page

Return key binding for Knockout.js

I’ve become a big fan of Knockout.js for building dynamic web interfaces. It’s one of the most “magical” frameworks I’ve seen since jQuery and Node.js, in that it’s great at what it does and makes building complex model/view interactions a breeze. Knockout provides a clean and quick event binding scheme, which allows you to work faster and write less code. However, making things faster and cleaner leads to… wanting even more speed and cleanliness!

So it was that I got tired of writing clunky controller scripts for managing text field input submission when the RETURN key is pressed. This seemed like an excellent opportunity to expand upon the Knockout framework to simplify this redundant task.

Here it is, just paste this into your project script somewhere after the Knockout.js include:

* RETURN key binding for Knockout.js
ko.bindingHandlers.returnKey = {
 init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
 ko.utils.registerEventHandler(element, 'keydown', function(evt) {
 if (evt.keyCode === 13) {

Once you’ve included that extension in your page’s JavaScript, you’ll now have a “returnKey” data binding available. You can use it like this:

<input type="text" data-bind="value:message, returnKey:send"/>
<button data-bind="click:send">Send</button>
That's it!