Though being Sunday, woke up early today. It is nice early morning underneath the warmth of morning sun, with coffee and newspaper in hand, and laptop at front. I was going through my twitter’s timeline and encountered a tweet saying Paul Walker is no more. It stuck! I mean, I have watched his every movie and Fast and Furious series was my favorite, and this promising actor, just died! Rest in peace, Mr. Paul Walker. Indeed, speed do kills.
Coming back to our post now. Continuing from previous discussion on knockout.js where we had created a simple application for getting the jest of what knockout can do. We are now to harness the power of knockout and see what more it can do. To begin with let’s have a look on computed properties.
Computed Properties
Computed property is something that uses the values of other properties to calculate its value. For example, let’s consider we have three properties “a”, “b” and “c”. While a=10 and b=20, the value of c is c=a+b. That is to say, the value of “c” is depending on the values of "both “a” and "b”. So we can cite “c” as our computed property.
Let us start with this very simple example of adding two numbers. The user will enter the numbers and on finished entering, the addition of both numbers will get displayed. So, first and foremost, we will create our view. Here is the HTML:
1: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <html lang="en">
4: <head>
5: </head>
6: <body>
7:
8: <div id="content">
9: <p>Number 1: <input type="text" data-bind="value: number1"/></p>
10: <p>Number 2: <input type="text" data-bind="value: number2"/></p>
11: <p data-bind="text: addition">Addition:</p>
12: </div>
13:
14: <script src="js/knockout 3.0.0.0.js" type="application/javascript"></script>
15: <script src="js/ViewModel.js" type="application/javascript"></script>
16:
17: </body>
18: </html>
Our view has two input text boxes where user can enter the number. These are bind with two properties number1 and number2 which are there in the ViewModel. The result of the summation will be displayed in the paragraph tag below, which is bind with yet another property, addition. Rest of the code is intact as with the previous post. Next is the ViewModel.
1: var ViewModel = function() {
2: this.number1= ko.observable();
3: this.number2= ko.observable();
4: this.addition = ko.computed(function(){
5: var num1 = parseInt(this.number1());
6: var num2 = parseInt(this.number2());
7: return num1 + num2;
8: },this);
9: }
10:
11: ko.applyBindings(new ViewModel());
As you can see, we're passing a callback function to the ko.computed
which specifies how it should compute its value. The number1 and number2 are first parsed to integer from text. Which are then summed and returned back. This is how the property addition get its value.
Run the HTML once. Fill the text boxes with the values and behold the magic happening.
Happy Coding!!!
0 comments