Controlling when the value is updated with Knockout.js

In the previous blog post about Knockout.js I showed why and how to get started with Knockout.js. And I explained that the reason I really like Knockout.js is that it is a very familiar way of working with its MVVM style.

I created a small demo where we could update the first and last name of a person and the ViewModel would combine the two and display the concatenated parts as the complete name. This worked just fine as soon as I started using observables except for one thing. Whenever I start typing the full name isn’t updated until the <input> control losses focus.


Quite often this will be good enough as the resulting value isn’t used right away but there are cases, like here, where it is and we want more frequent updates.


The value binding

As it turns out the value data binding has an additional option, the valueUpdate, that controls when the value, and therefor the computed observable full name is updated. By adding that to the data-bind expression we can get real time updates. There are several options but for these real time scenarios using the value of afterkeydown works best.

The markup now looks like this:


    <legend>Enter person</legend>


        First name:

        <input type="text" data-bind="value: firstName, valueUpdate: 'afterkeydown'" />



        last name:

        <input type="text" data-bind="value: lastName, valueUpdate: 'afterkeydown'" />



        Full name: <span data-bind="text: fullName"></span>



The JavaScript is unchanged and looks like this:

$(function () {

    var viewModel = {};

    viewModel.firstName = ko.observable("Maurice");

    viewModel.lastName = ko.observable("de Beijer");

    viewModel.fullName = ko.computed(function () {

        return viewModel.firstName() + " " + viewModel.lastName();






With this change the full name is updated with each character entered.



Sweet Smile






Leave a Reply

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