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.

image

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:

<fieldset>


    <legend>Enter person</legend>


    <p>


        First name:


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


    </p>


    <p>


        last name:


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


    </p>


    <p>


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


    </p>


</fieldset>

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();


    });


 


    ko.applyBindings(viewModel);


});



 



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



image



 



Sweet Smile



 



Enjoy!



 



[f1]
[f2]

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>