Knockout: Input fields

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.

3-knockout-input-fields

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.

4-knockout-input-fields

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.

5-knockout-input-fields

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.

6-knockout-input-fields

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

7-knockout-input-fields

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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