Blueberrylady
Blueberrylady

Reputation: 55

Anybody who can help understand this Knockout Observable?

I am a complete beginner in Software Development, and got introduced to a project which I have a hard time understanding and knowing where to start

this.isConfirmationCar = ko.computed(() => {
  if (this.selectedTemplate() && this.selectedTemplate().Id ===
     <number>Enums.PolicyEmailTemplates.ConfirmationOfCoverCar) {
       return true;
  } else {
       return false;
  }
});

Upvotes: 1

Views: 65

Answers (2)

Akrion
Akrion

Reputation: 18525

What you have there is a computed observable which is nothing more but a function which inside of its body tracks ANY other observable used. Not only it tracks it but it would execute itself again and again on those tracked observables values mutating.

Computed observables are extremely useful. Note that they have various "options" in terms of how to defined them and some interesting siblings like the pureComputed observables.

In this example the computed isConfirmationCar is used to track the values of the other observables selectedTemplate and selectedTemplate. The moment any of those change that computed with refresh its value which is why it is used in this context for tracking isConfirmationCar.

Hope this helps.

Upvotes: 1

bsod_
bsod_

Reputation: 941

It looks to be returning a boolean value and storing it within this.isConfirmationCar. This being either true/false dependant on the argument defined as -

{ if (this.selectedTemplate() && this.selectedTemplate().Id === Enums.PolicyEmailTemplates.ConfirmationOfCoverCar) { return true; } else { return false; }

FYI - Knockoutjs has a great website with an excellent tutorial http://learn.knockoutjs.com/#/?tutorial=intro

It covers the ko.computed function in the intro worth a look!

Upvotes: 3

Related Questions