KnockoutJS Computed Observable

In the last article we studied how to create observables. In this article we shall study knockoutJS computed observables. Computed observables are basically functions that act upon two or more than two simple observable and return the computed value. The computed value can either be some of two numbers, or string concatenation or virtually anything. If value for any of the simple observable changes, the computed variable is updated accordingly.

Let’s take example of first name and last name of student. Suppose you want to create a page that takes student’s first name and last name in two seprate text fields and then display them in a paragraph. You can do so via computed obervables. Let’s have a look at the following code snippet.

KnockoutJS Computed Observable Example

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
    
</head>

<body>
    

   <p>Student First Name: <input data-bind="value: StudentFName" /></p>
  <p>Student Last Name: <input data-bind="value: StudentLName" /></p>
   <p>Student  <strong data-bind="text: StudentFullName"></strong> obtained 90% marks.</p>

   <script>

   function StudentModel() {
     this.StudentFName = ko.observable('');
     this.StudentLName = ko.observable('');
     this.StudentFullName = ko.computed(function() {
        return this.StudentFName() + " " + this.StudentLName();
    }, this);
   }
       
       

  
   ko.applyBindings(new StudentModel());
   </script>
    
</body>
</html>

Download the code Try the code

In the above code in html view, we have to input boxes one for the first name and the second for the last name. The data-bind attribute binds StudentFName attribute to first input box and the StudentLName to the second input box. In the paragraph, the text property is bind to “StudentFullName”.

Now if you come down to the JavaScript view model. You should see a StudentModel with three member variables. StudentFName, StudentLName and StudentFullName. Here the first two variables are assigned as observable while the last variable is declared computed variable. The knockoutJS computed observable contains a function which basically returns the concatenation of the first two variables.

Now, if you open the above web page in browser, you should see two empty text fields. If you enter anything in the first text field it will be displayed in the bold form in the paragraph tag below. Similarly, if you enter anything in the second text field. It will appear appended after the text in the first text field inside the paragraph below. Updating the first name or last name shall also update the computed full name.

KnockoutJS Observables

Now we know that HTML DOM elements and ViewModel are bound to each other via data-bind concept. The information between the DOM and JS ViewModel is passed via Observable which are responsible for two way dependency tracking.In this article we shall briefly review KnockoutJS observables.

Observables are created when we create a new ViewModel and create some properties inside it. When the ViewModel is bound to HTML DOM via data-bind, knockoutJS observables keep record of the both. In case if the ViewModel is updated via JavaScript, the corresponding values in the HTML DOM are also updated. Similarly, if values are changed on the HTML side, the corresponding ViewModel properties are accordingly updated. This is what observable does. Now, take a look at a very simple example to see observable in action.

Observable Example

To create an observable on any ViewModel variable simply assign ko.observable(”); to that value. We shall see that in the following code snippet. Take a look at it.

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
    
</head>

<body>
    

   <p>Student Name: <input data-bind="value: StudentName" /></p>
   <p>Student  <strong data-bind="text: StudentName"></strong> obtained 90% marks.</p>

   <script>

   function StudentModel() {
       this.StudentName = ko.observable("");
   }

  
   ko.applyBindings(new StudentModel());
   </script>
    
</body>
</html>

Download the code Try the code

Let’s start from the paragraph tag at the top. Inside the paragraph we have the input element. The data-bind attribute here binds the value entered in this input tag to the “StudentName” attribute of the StudentModel view model. Next again data-bind binds the value of the StudentName attribute to “text” attribute of the paragraph. Now if you enter any name in the text box and press the enter key. The corresponding value in the paragraph shall be updated immediately. This is because we have used “observable” with StudentName.

Now come to the script section. Here we create a ViewModel named StudentMode. StudentModel has one attribute StudentName. The ko.observable is called on “StudentName” to change it to observable property. Therefore, this “observable” keeps an eye on “StudentName”. Thus whenever value for StudentName is updated anywhere, it is updated through out the application.

KnockoutJS Environment Setup

The last article provided a very brief introduction to KnockoutJS. In this article we shall get our hands dirty and write our first KnockoutJS application. But before that we shall see how we can perform knockoutJS environment setup so that we can run our knockoutJS applications locally.

KnockoutJS Environment Setup

There are two ways to locally setup your knockoutJS environment. Simply go to this website and download the knockoutjs library and then reference it via script tag.

The other way is to use a KnockoutJS cdn and simply reference it in your applications. In all of the code samples in this article series we shall use the second approach. So in the header section, inside the src attribute of your script tag, add this link “https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js”. Take a look at the first example to see how things actually work.

First Application

Take a look at the following code snippet, we shall explain the code in the section that follows:

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
    
</head>

<body>
    
<p>Student Name: <strong data-bind="text: Name"></strong></p>
<p>Student Age: <strong data-bind="text: Age"></strong></p>
    
    
<script>
    function StudentModel() {
    this.Name = "Thompson";
    this.Age = "20";
}

ko.applyBindings(new StudentModel());
    
</script>
    
</body>
</html>

Download the code Try the code

Now carefully take a look at the above code. Inside the body tag you can see two paragraph tags. This is basically an html view. After the paragraph tags, we have some JavaScript code. This code is JS view model. In this script we create a model named StudentModel. The model has two properties, name and age. To bind this JS view model to the HTML DOM we use ko.applyBindings method and pass it the name of the mode.

Now again come back to the paragraph tags we created earlier. Here we can access the members of the view model via data-bind attribute. This attribute takes two values, first is the HTML attribute that you want to change and second is the value of the property of the view model. For instance in the paragraph tag, we use data-bind to assign value of Name and Age properties of StudentModel to the text attribute of the two paragraphs.

Knockout JS Tutorial

Welcome to another series of tutorials on one of the most advanced and latest JavaScript framework i.e. KnockoutJS. Putting it simple, KnockoutJS is a framework similar to AngularJS or JQueryUI and is used to create responsive and beautiful user interfaces. It is important to note here that unlike node.js, KnockoutJS is a client side library. KnowckoutJS is based on MVVM architecture which fosters separation of concerns by separating application into application model, view and view model. This tutorial provides a brief KnockoutJS Introduction.

Prerequisites

KnockoutJS is an advanced JavaScript framework. In order to understand tutorials in this series, you should have advanced understanding of HTML, CSS and JavaScript. If you do not have solid grasp over these technologies I would suggest you to first study them and then come back here and start the tutorials.

KnockoutJS Features

Following are some of the most prominent features of KnockoutJS.

Simple Data Binding

It is very simple to bind application data with html UI elements via simple and easy data-binding syntax. This helps improve responsiveness of the application.

Two Way Binding

Binding between html elements and application data is two way. If you change the value of the application data, it is immediately reflected by the UI element and vice versa.

Reusable Templates

KnockoutJS contains builtin templates that help create UI applications in a rapid manner.

Easily Enhanced

You can easily add new features to knockoutJS applications.

Advantages of KnockoutJS

  • KnockoutJS should not be seen as a replacement to any other JavaScript framework. Rather it is a unique in a sense that it is based on MVVM and provides data binding capabilities that can be used to create complex user interfaces.
  • KnockoutJS library is very light weight and puts no extra load on the webpage.
  • Similarly, knockoutJS is absolutely free and open source. It has large community support as well.
  • KnockoutJS comes with detailed documentation and comes with lots of online help.

This tutorial merely contained KnockoutJS introduction. In the upcoming tutorial, we shall see how to setup knockoutJS environment and how to run our first application.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .