Builtin Bindings in Knockout.js: Controlling Text and Appearance

Setting up Visual Studio 2013 for Knockoutjs Development
Create your First MVVM based JavaScript App in two simple steps using Knockoutjs

In simpler terms we can define Knockoutjs binding as a mechanism to establish a relationship between a view and a ViewModel. A view takes a user action and passes the instruction to a ViewModel. One of the most popular examples of this could be clicking on a button or selection of an item on the View by the user. After each action of the user, the view gets the task of instructing the ViewModel about it. This is done through the binding. On the other hand we can define the binding as manipulating DOM elements and their appearance on the basis of ViewModel properties. The binding establishes the relationship between a View and a ViewModel.

relationship between View and ViewModel
 
KO Bindings can be categorized in the following categories:

  1. Controlling Text and Appearance
  2. Controlling Flow
  3. Controlling User Actions like Click, Submit and so on.

If required, you can create a Custom Binding as well.  In this article we will focus on bindings that control text and appearance. Those bindings are as follows:

bindings

Now one by one let us have a look at various text controls and appearance bindings.
 
Visible binding

You use a visible binding to determine when an element in the DOM should be visible or when it should not be. This binding is very simple to use.
 
Let us say you have a ViewModel as below:

var viewModel = {
          displayko.observable(false)
      };

 
You can use visible binding on the view as below:

 <div data-bind="visibledisplay">
        <h2>hey I am visible through visible binding </h2>
    </div>

 
 Some points about visible binding is worth explaining here. If the value of a ViewModel property will resolve to one of the following values then the bound DOM element view property will be set to block.

  1. Null
  2. undefined
  3. number zero
  4. Boolean false

For DOM elements if a ViewModel property value yields false then the visible binding will always have a higher priority than the CSS attributes.

ViewModel property
 
Text binding

 You use text bindings to display a text on the View. You can do text binding with elements like:

  • <h1>,<h2>
  • <em>
  • <span>
  • <input>
  • Practically you can do text binding with any element on View.

Let us suppose you have ViewModel as below:

  var viewModel = {
        message : "hey welcome to KO "
    };


You can do text binding on the View as below:

<div>
      <h2 data-bind="text : message"></h2>
  </div> 

 
If the ViewModel property contains a HTML encoded value and you bind that property on the View using text binding then:
 

var viewModel = { 
         message"hey welcome to KO ",
         messagehtml:"<i>hello there</i>"
     };

 
 
Binding is done as in the following:

<div>
        <h2 data-bind="text : message"></h2>
        <span data-bind="textmessagehtml"></span>
    </div>

    
You will get an output HTML encoded value as plain text. It will not be rendered. You will get ouput as below:

HTML encoded value as plain text
 
In text binding:

  • All the previous values of the Element on the View will be overwritten

  • If a ViewModel property contains any value than string or number then in text binding that value will get displayed as value.toString()

HTML  binding

You use HTML binding to set the InnerHtml property of a View’s Elements. So let us use a ViewModel with a property value encoded HTML value.

var viewModel = {
 
         message"hey welcome to KO ",
         messagehtml:"<h1>hello there</h1>"
 
     };

HTML binding can be done as in the following:

<div>
        <h4 data-bind="text : message"></h4>
        <span data-bind="htmlmessagehtml"></span>
    </div>

Now the View will render HTML from the ViewModel.  HTML binding always sets the innerHtml attribute of the Element and the text binding sets the innerText property. You should be cognizant of that when using HTML binding because it may cause potential injection of a script into the view.
 
CSS binding

You use CSS binding to apply a CSS class to elements on the View.  Let us say you have a CSS class defined as below:

.red
 {
     color:red
 }

 
You want to apply a red background to the div on a condition from the ViewModel property. Let us assume we have a ViewModel as in the following:

var viewModel = {
 
         message"hey welcome to KO ",
         messagehtml"<h1>hello there</h1>",
         warningmessage : false 
 
     };

Let us assume that we want to apply the red class from CSS on the basis of the warningmessage property of the view. We can do CSS binding as below:

<div data-bind="css: {red : warningmessage}">
            hello world
   </div>

 
Let us see how to work with dynamic classes in CSS binding. Assume that we have the following classes:

.red
{
    color:red
   
}
.blue 
{
    color:blue 
}
.green{
    color : green
}

 
We need to dynamically bind one of these classes to an element on a View. Suppose we have a ViewModel as below:

var viewModel = {
 
         message"hey welcome to KO ",
         messagehtml"<h1>hello there</h1>",
         messagelevel : 10 
 
     };

 
On the basis of the ViewModel property messagelevel we need to apply a CSS class dynamically. To do this a computed observable is required. A computed observable will return a CSS class.

 viewModel.colorMessage = ko.computed(function () {

        if (this.messagelevel > 0)
        {
            return 'green';
        }
        else if(this.messagelevel <0)
        {
            return 'red';
        }
        else if(this.messagelevel==0)
        {
            return 'blue';
        }
    }, viewModel);

 
And the CSS binding of a View can be done as follows:

<div>
        <div data-bind="csscolorMessage,
             htmlmessagehtml">          
        </div>       
    </div>

In this article we learn various bindings that help to control the text and appearance of elements. I hope you find this article useful. Thanks for reading.

Next Recommended Readings