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.

<<< Model-View-ViewModel (MVVM)KnockoutJS Computed Observable >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .