KnockoutJS Computed Observables KnockoutJS Computed Observables

Computed Observables with Knockoutjs are functions that are dependent on one or more other observables, and will automatically update whenever any of these dependencies change.


`this` context with ko computed observables and subscribe

In JavaScript, the `this` variable inside a function (like a computed observable or a Knockout subscribe) function can be an extremely useful variable to access related properties to your observable.

Learning the following behavior has opened many doors for me when leveraging the Knockout.js framework.

This Knockout js tutorial will demonstrate through an example using a computed observable inside my ViewModel.

Creating a basic Knockout ViewModel

Let's begin with a simple ViewModel example:

<!DOCTYPE html>
<html>
<head>
<title>Data Binding with KnockoutJS</title>
</head>
<body>
<h1>Hello <span data-bind="text: fullName"></span></h1>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js'></script>
<script>
var viewModel = function() {
this.person = {
firstName: 'End',
middleName: 'Your',
lastName: 'If'
};
this.fullName = ko.computed(function() {
return this.person.firstName
+ ' ' + this.person.middleName
+ ' ' + this.person.lastName;
});
};
ko.applyBindings(viewModel);
</script>
</body>
</html>

As you can see inside my ViewModel, inside my fullName computed observable, this is referencing my outer ViewModel; sometimes useful, sometimes not.

In this case it's not quite as useful because I need to reference the person object 3 separate times.

Using this with a computed observable

In this next example I am going to override the default this by passing the person object and defining it as the new this for my computed observable.

This also allows me to remove the 3 references to the person object and just use this as it has been changed to the person object.

<!DOCTYPE html>
<html>
<head>
<title>Data Binding with KnockoutJS</title>
</head>
<body>
<h1>Hello <span data-bind="text: fullName"></span></h1>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js'></script>
<script>
var viewModel = function() {
this.person = {
firstName: 'End',
middleName: 'Your',
lastName: 'If'
};
this.fullName = ko.computed(function() {
return this.firstName
+ ' ' + this.middleName
+ ' ' + this.lastName;
}, this.person);
};
ko.applyBindings(viewModel);
</script>
</body>
</html>

I personally find this is even more useful when inside of a JavaScript array of objects. This final example will create a list of people using the similar concept.

Once the array of people is created, the previous h1 tag is wrapped in a Knockout foreach loop to display all fullName's of the people.

When you are setting up your data bindings I have an article about Uncaught ReferenceError: Unable to process binding in the odd scenario that an unclear binding issue has occurred.

<!DOCTYPE html>
<html>
<head>
<title>Data Binding with KnockoutJS</title>
</head>
<body>
<!-- ko foreach: people -->
<h1>Hello <span data-bind="text: fullName"></span></h1>
<!-- /ko -->
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js'></script>
<script>
var viewModel = function() {
this.people = [
{
firstName: 'End',
middleName: 'Your',
lastName: 'If'
},{
firstName: 'End',
middleName: 'Your',
lastName: 'If'
}
];
for (var x = 0; x < this.people.length; x++) {
var person = this.people[x];
person.fullName = ko.computed(function() {
return this.firstName
+ ' ' + this.middleName
+ ' ' + this.lastName;
}, person);
}
};
ko.applyBindings(viewModel);
</script>
</body>
</html>

Writeable computed observations

Beginners may be wishing to skip this section. Writeable computed observables are fairly advanced and do not need any additional knowledge.

This makes computation of observed information normally read-only.

It might appear strange, that computations can be written into a text. You simply require your own callback function.

It is then possible to use compute observable written as the same as observables, but with your own custom logic intercepting reads and writes.

It's a powerful option which offers several uses.

Accessing an Observable

Observations can be defined using functions to get the desired values and get them. If you set the variables in direct order as variables, you can destroy this observable.

Similarly, a value can be retrieved from a corresponding Alert. In the event the observable was alerted without brackets, the script could produce a huge chunk of Java script code.

The second type for observable is an observable array.

PureComputable Observables

Since Knockout 3.2 has been introduced a new kind of observer called pureComputedObservable called for use. There's a very similarity between computations and observation; several improvements in processing and memory are provided.

It is derived from pure function programming terminology.

A commonly used example of how this type is observable in which first and last names are incorporated into one computations-observable.

How dependency tracking works?

Beginners will not have a problem with Ko's automatic tracking and UI update functionality. In fact, the whole thing was quite straightforward. It's an algorithm for tracking dependencies.

So you can dependencies dynamically, A and B could decide whether or not to depend on them, so, it is only after you change A's current B or C choice that you should re-evaluation occur.

Computed observations

Can I display the name of my child's first name? These functions depend upon one or multiple observables and can update automatically based upon the changes to these dependencies.

If a viewmodel class is given in a table, the function AppViewModel() can be used:

this.Firstname = ko.observable(Bob); 
this.Lastname = ko.observable('Smith');

Determining if a property is a computed observable property

Some scenarios allow programmatic analysis of whether the data are computed as observable. Knockout utility functions are required for this task. In some cases, you can exclude computed observations from data sent back from your server.

If (myObject. has Own Property(prop) & &! ko.isCompulsed[memo]) - result_prop = my_object[prop]

Pure computed observations

A computed observing object is considered computed observing if this observation is only based on calculations and returns its value.

Knockout is a powerful tool which allows for smooth revaluation and memory consumption.

Hopefully this will help you as much as it did me.

Published on Sep 2, 2022

Tags: foreach | Knockout js Tutorial | observable | this

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.