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 ObservablesKnockoutJS Visible Binding >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .