Computed Observables in Knockout.js

In Knockout.js Computed Observables is the functions and all the computed observables dependend on one or more Observables and useful for the automatic updates whenever its underlying observables change. A Computed Observable is derived from the one or multiple other Observables, so Computed Observables are read-only. Normally, we can use a writable computed observable exactly the same as the regular observable, with the custom logic intercepting all reads and writes.

Pure Computed Observables

Computed Observables can be declared as Pure Computed observables by simply calculating and returning the value and also working on the other objects for performing the modifying operations. Pure Computed Observables are also useful in Knockout to manage memory usage efficiently and re-evaluate.

The following are the properties in Computed Observables:

  • ko.isComputed
  • ko.isObservable
  • ko.isWritableObservable

Writable Observable

As we know Computed Observables are read-only but it is possible that one can make Computed Observables writable. For doing that we need to provide a callback function that does the operations on the written values.

Step 1

Start Visual Studio.


Figure 1: Start Visual Studio 

Step 2

Now we create the website, click on File, tehn go to New and click on the Web Site.


Step 3

Now we will add the Knockout.js library to the website. To do this we will manage the NuGet Package and for that we will right-click on the website and click on the NuGet Packages.


Figure 3: Manage NuGet 

Step 4

After adding the Knockout.js library, next we need to add the web form to the website by right-clicking and add a web form to the website.

 

Figure 4: Add Web Form
 
Step 5

Now we need to write the code for the Computed Observables.

In this code I have used the two observables and one Computed Observables to show how Computed Observables work dependent on one or more Observables and in the default I have passed the 30 and 40 values in the parameters.


In the image I want to describe that Computed Observables dependent on the normal Observables.

Step 6

After writing the code we will execute the website using the F5 key. After the execution the following window appears on the screen.


Step 7

If we change in the first Observable then the Computed Observable, the Average value, is automatically changed, that indicates that the Computed Observable is dependent on the observables.

 

Summary

This article explained how Computed Observables work and how to use the Computed Observables in Knockout.js in the Visual Studio 2013.

I hope this article will be helpful for the beginners if they want to use observables in Knockout.js.

Up Next
    Ebook Download
    View all
    Learn
    View all