Modes of Communication/Types of Binding in KnockoutJS


In this blog, we will see 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 the MVVM pattern, we need to follow the modes of communication while designing our web pages.
There 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.
  1. var viewModel = {  
  2.     userName: ko.observable("Jagan"),  
  3.     userFullName: "Jaganathan B"  
  4. }; 
Consider the above code, we have a observable property called userName as well as simple js property called userFullName.
  1. <b>One-way communication </b>  
  2. <p>Login name: <input data-bind="value: userFullName" /></p>  
  3. <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 on the page, but the changes happened 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. 
  1. <b>Two-way communication </b>  
  2. <p>Login name: <input data-bind="value: userName" /></p>  
  3. <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.
  1. <b>One-way communication with observable</b>  
  2. <p>Login name: <input data-bind="value: userNameJS()" /></p>  
  3. <p>New login name is : <span data-bind="text: userNameJS()"> </span> </p>