English 中文(简体)
KnockoutJS - Dependency Tracking
  • 时间:2024-11-03

KnockoutJS - Dependency Tracking


Previous Page Next Page  

KnockoutJs automatically tracks the dependencies when the values get updated. It has a single object called dependency tracker (ko.dependencyDetection) which acts as an intermediate between the two parties for subscribing the dependencies.

Following is the algorithm for dependency tracking.

dependency tracking

Step 1 − Whenever you declare a computed observable, KO immediately invokes its evaluator function to get its initial value.

Step 2 − Subscription is set up to any observable that the evaluator reads. In an apppcation, the old subscriptions which are no longer used are disposed.

Step 3 − KO finally notifies the updated computed observable.

Example

<!DOCTYPE html>
<html>
   <head>
      <title>KnockoutJS How Dependency Tracking Works</title>
      <!-- CDN s-->
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
         type = "text/javascript"></script>
   </head>
   
   <body>
      <span>
         <form data-bind = "submit: addFruits">
            <b>Add Fruits:</b>
            <input data-bind =  value: fruitToAdd, valueUpdate: "afterkeydown" />
            <button type = "submit" data-bind = "enable: fruitToAdd().length > 0">Add</button>
            <p><b>Your fruits pst:</b></p>
            <select multiple = "multiple" width = "50" data-bind = "options: fruits"> </select>
         </form>
      </span>
      
      <script>
         var Addfruit = function(fruits) {
            this.fruits = ko.observableArray(fruits);
            this.fruitToAdd = ko.observable("");
            
            this.addFruits = function() {
               
               if (this.fruitToAdd() != "") {
                  this.fruits.push(this.fruitToAdd());   // Adds a fruit
                  this.fruitToAdd("");                   // Clears the text box
               }
                
            }.bind(this);                                // "this" is the view model
         };

         ko.applyBindings(new Addfruit(["Apple", "Orange", "Banana"]));
      </script>
      
   </body>
</html>

Output

Let s carry out the following steps to see how the above code works −

    Save the above code in dependency_tracking.htm file.

    Open this HTML file in a browser.

    Enter any fruit name and cpck the Add button.