Modes of Communication/Types of Binding in KnockoutJS

In this blog, we will see about the types of bindings/modes of communication[views to viewmodel] in the KnockoutJS.

Basically, in MVVM pattern like Microsoft Silverlight, we might be following the modes of communication or you may call types of binding.

As KnockoutJS designed to follow MVVM pattern, we need to follow the modes of communication while designing our web pages.

The are two types of bindings/communications available in KnockoutJS.

  1. One-way communication
  2. Two-way communication 

What is one-way communication?

One-way communication can be implemented by binding the simple javascript property from viewmodel to the view.

 var viewModel = {
        userName: ko.observable("Jagan"),
    userFullName: "Jaganathan B"
    };

Consider the above code, we have a observable property called userName as well as simple js property called userFullName.

<b>One-way communication </b>
<p>Login name: <input data-bind="value: userFullName" /></p>

<p>New login name is : <span data-bind="text: userFullName"> </span> </p>

if you binding the userFullName with the view, then the initial value in the js property will be displayed in the page, but the changes happended in the textbox value will not be updated to the property as it is a simple javascript property.

What is two-way communication?

Two-way communication can be implemented by binding the observable property to the view. The observable property userFullName from the above example, can be used for two-way communication. 

<b>Two-way communication </b>
<p>Login name: <input data-bind="value: userName" /></p>

<p>New login name is : <span data-bind="text: userName"> </span> </p>

So the observable property userName will communicate to the view as well as viewmodel. Even if it is observable, while binding to the view if you add () to the observable [call the observable function userName] like the below, it will act as one-way binding. See the below example.

<b>One-way communication with observable</b>
<p>Login name: <input data-bind="value: userNameJS()" /></p>

<p>New login name is : <span data-bind="text: userNameJS()"> </span> </p>

Example:

 
Ebook Download
View all
Learn
View all