How Ko is automatically updated
Beginners can skim the article, and if you're a inquisitive developer, this section will tell you how Ko is implementing dependency tracking and UI updates automatically.
Actually very simple, KO's dependency tracking algorithm is as follows:
- When you declare a computed monitoring property, Ko immediately calls its associated function to get its initial value.
- When the related function is running, KO will establish a subscription to the relevant monitoring properties (including other computed monitoring properties) and read their values. The subscription callback function is set to run the subscription function again, looping through this process.
- When there is a new value, KO will notify you of the calculated monitoring property to give the value back to the user.
Using Peek to control dependencies
Knockout automatic dependency tracking is usually not what you want, but you may sometimes need to control the monitoring properties that update the value of the dependency property, especially if the dependency property performs certain operations, such as an AJAX request. The Peek method can help you control a monitoring property or dependency property without having to create dependencies.
In the following example, the dependency property reloads a monitoring property named Currentpagedata with the Ajax method and the other two monitoring property parameters. When pageindex changes, the dependency property is updated, but the change in SelectedItem is ignored because it is controlled by the Peek method. In this case, the user may want to use the current value of SelectedItem for tracking only when the data is loaded.
Ko.computed (function() { var params = { this. PageIndex (), This . Selecteditem.peek () }; $.getjson (this);
As the above example, if you want to do spa, this way is very useful oh ~. If you want to prevent some too frequent monitoring property updates, you can refer to the first section of chapter two to delay or suppress change notification
Knockoutjs 3.X API Third Chapter Computing Monitoring properties (3) Ko How to implement dependency tracking