KnockoutJS - SPLessons

Knockout.js Computed Obeservables

Home > Lesson > Chapter 4
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Knockout.js Computed Obeservables

Knockout.js Computed Obeservables

shape Introduction

This chapter demonstrates about the Knockout.js Computed Observables which is a function is dependent on one or more other observables and it will update changes automatically when dependency change and following are the concepts are covered in this chapter.
  • Using Computed Observable
  • Managing This
  • Writable Computed Observables

Using Computed Observable

shape Description

Computed Observables are dependent on one or more observables and which can update automatically whenever observable get changes these observable can be chained. The syntax below demonstrates the Computed Observables. [code] this.varName = ko.computed(function(){ ... ... // function code ... },this); [/code] The code below demonstrates the Computed Observables as shown below. [html] <!DOCTYPE html> <head > <title>KnockoutJS Computed Observables</title> <script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"></script> </head> <body> <p>Enter first number: <input data-bind="value: a" /></p> <p>Enter second number: <input data-bind="value: b"/></p> <p>Sum := <span data-bind="text: totalSum"></span></p> <script> function MyViewModel() { this.a = ko.observable(10); this.b = ko.observable(40); this.totalSum = ko.computed(function(){ if(typeof(this.a()) !== "number" || typeof(this.b()) !== "number"){ this.a(Number(this.a())); //convert string to Number this.b(Number(this.b())); //convert string to Number } total = (this.a() + this.b()) ; return total; },this); } ko.applyBindings(new MyViewModel()); </script> </body> </html> [/html] Result By running the above code in a preferred browser user can get the following output as shown in below image. In the above program, Enter first number and second numbers are accepting the values and the next line Sum printing the Sum of these 2 numbers. a and b are the Number type Observables if they are initialised for the first time inside View Model In KO every input is accepted from the UI in a string format. So the user needs to convert them into number format to perform arithmetic operations. The sum has calculated the sum of the Numbers displayed in UI.

Managing This

shape Description

The second parameter to ko.computed is that characterizes the estimation of this while passing the processed recognizable. Without passing it in, it would not have been possible to refer to this.firstName() or this.lastName(). Experienced JavaScript coders will see this as self-evident, however in the event that despite everything you're becoming more acquainted with JavaScript it may appear strange is as shown in below snippet. [code] function MyViewModel(){ self = this; self.a = ko.observable(10); self.b = ko.observable(40); this.totalSum = ko.computed(function(){ if(typeof(self.a()) !== "number" || typeof(self.b()) !== "number"){ self.a(Number(self.a())); //convert string to Number self.b(Number(self.b())); //convert string to Number } total = (self.a() + self.b()) ; return total; }); } [/code] Dependency Chains just work The user can also create the Dependency chains in order to create these chains users need to follow the below points.
  • An Observable called item representing a set of items.
  • another noticeable called selectedIndexes putting away which item indexes have been "selected" by the client.
  • A computed observable called selectedItems which profit an array of object items comparing to the selected indexes.
  • another computed observable which profits true or false relying upon whether any of selectedItems has some property. Some UI elements, similar to a button, may be enabled or disabled based on this value.

Writable Computed Observables

shape Description

Computed observables have an esteem that is processed from different observables. In which computed observables are normally read-only. What may appear to be shocking, then, is that it is possible to make computed observables writeable? The user simply needs to supply own particular callback function which accomplishes something sensible with written qualities. The user can use writeable computed observable precisely like a regular observable - performing two-way binding with DOM elements; with his own particular custom logic intercepting all reads and writes. Which is an effective element with an extensive variety of conceivable uses! The code below demonstrates the writable computable Observable as shown below. [html] <!DOCTYPE html> <head > <title>KnockoutJS Writable Computed Observable</title> <script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script> </head> <body> <p>Enter your birth Date: <input type="date" data-bind="value: rawDate" > </p> <p> <span data-bind="text: yourAge"></span></p> <script> function MyViewModel(){ this.yourAge = ko.observable(); today = new Date(); rawDate = ko.observable(); this.rawDate = ko.pureComputed({ read: function(){ return this.yourAge; }, write: function(value){ var b = Date.parse(value); // convert birth date into milliseconds var t = Date.parse(today); // convert todays date into milliseconds diff = t - b; // take difference var y = Math.floor(diff/31449600000); // difference is converted into years. 31449600000 milliseconds form a year. var m = Math.floor((diff % 31449600000)/604800000/4.3); //calculating months. 604800000 milliseconds form a week. this.yourAge("You are " + y + " year(s) " + m +" months old."); }, owner: this }); } ko.applyBindings(new MyViewModel()); </script> </body> </html> [/html] Result By running the above code in a preferred browser user can get the following output as shown in below image.

Summary

shape Key Points

  • Computed Observable depends on or more Observables.
  • with out this Observables refering is not possible.