KnockoutJS – Observables

Dependency Tracking

3 concepts in which KnockoutJS is build upon is:
– Through observables dom elements and ViewModel exchange information
– Bindings between UI and ViewModel
– Templating web applications

To make it observable declare as:
this.property = ko.observable(‘value’);

Let’s try below Observables example:

<!DOCTYPE html>
<head>
<title>KnockoutJS - Observables</title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"></script>
</head>
<body>
<!-- This is input box, used data-bind attribute to bind name to ViewModel -->
<p>Put your name here: <input data-bind="value: name" /></p>

<!-- To print value use data-bind type as text -->
<p>Hi <strong data-bind="text: name"></strong> How are you?</p>

<script>
function AppViewModel() {
<!-- ko.observable keeps an eye on name variable, any modification in data it change the respective places with changed value -->
this.name = ko.observable("John!");
}
ko.applyBindings(new AppViewModel());
</script>
</body>
</html>

Computed Observable is a function which is dependent on one or more Observables. For any Observables change it will automatically update.

Syntax:

 this.variable = ko.computed(function(){
 ...
 },this);

Lets see the example below:

<!DOCTYPE html>
 <head>
 <title>KnockoutJS - Observables</title>
 <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"></script>
 </head>
 <body>
 <p>1st no: <input data-bind="value: a" /></p>
 <p>2nd no: <input data-bind="value: b"/></p>
 <p>Multiply: <span data-bind="text: total"></span></p>
 <script>
 function AppViewModel() {
 this.a = ko.observable(5);
 this.b = ko.observable(3);
 this.total = ko.computed(function() {
 return this.a() * this.b();
 }, this);
 }
 ko.applyBindings(new AppViewModel());
 </script>
 </body>
 </html>

Leave a Reply

Your email address will not be published. Required fields are marked *