Knockout: Input fields

Please see my other JavaScript articles.

Using knockout.js to dynamically reflect changes to input fields.

As described on the Knockout.js website, it provides impressive features such as: Declarative Binding, Automatic UI Refresh, Dependency Tracking, and Templating.

In this article, I will illustrate Declarative Binding and Automatic UI Refresh using some basic input fields.

First, I’ll begin with a simple page containing just a couple name fields.

1-knockout-input-fields 2-knockout-input-fields

The HTML above defines my “View,” the logical layer of my application which represents the User Interface (UI).
To enable knockout.js functionality I must add a “script” tag within the “head” page.


Now I’m ready to build my View Model, the piece which will represent my Developer entity to the View.
Note: It’s important that I place my “script” tags below the View so that the JavaScript “sees” the appropriate attributes.
In this section I will build a model to represent a typical developer to the application.
The purpose of the model is to adhere to “separation of concerns” by keeping attributes and behavior of my entities, in this case developers, separate from the UI layer of the application.


Now that I have a View and a View Model, I need to enable Knockout to wire them together.
In Knockout, you wire them together by applying a binding.


With my View Model bound to my View, the last step to cause the View to reflect changes made to the View Model is to update the View’s properties.
Where I wish the View Model’s attributes to be displayed within the View, I simply apply “data-bind” property to an HTML control and specify which View Model attribute.
In this case, I was to display as text the “firstName” attribute.


Now when I change my first name attribute to “Earnest” in the View Model, it’s automatically reflected in the View.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s