knockout foreach computed value

1.6k Views Asked by At

I am trying to add a computed value to my viewModel object. And I am using foreach to create a table of rows. I am not able to get around this computed function.

I am trying to do this.

viewModel =
 {
   objectName: ko.observable([
       { value: "", triggerValue: "0"},
       { value: "", triggerValue: "1"},
       { value: "", triggerValue: "1"} 
   ]),
 };

viewModel.objectName().value= ko.computed(function() {
      return this.objectName().triggerValue= "0" ? "Apple" : "Microsoft";
    }, this);

I want the viewModel objectName output to look like

{value: "Apple", triggerValue: "0"},
{value: "Microsoft", triggerValue: "1"},
{value: "Microsoft", triggerValue: "1"}

Thanks. KDK

1

There are 1 best solutions below

1
On BEST ANSWER

Several mistakes going on here

  1. you are using an observable instead of observableArray, technically an observable can store an array, but you are better off using an observableArray
  2. you are trying to tie a computed to objectName().value, but object name is suppose to be an array so it would not have a value, it would ideally be like this objectName()[1].value.
  3. This is not how to assign properties, ko.computed is not a replacement for a function, computed are for monitoring existing observales and and re calculating when a change is made in one of the monitored observables.

I would do something like this.

viewModel =
 {
   objectName: ko.observable([
     { value: setType(0), triggerValue: "0"},
     { value: setType(1), triggerValue: "1"},
     { value: setType(1), triggerValue: "1"} 
 ]),
};

function setType(trigger){
   return trigger = "0" ? "Apple" : "Microsoft"
}

or better yet

viewModel =
 {
   objectName: ko.observable([
   setVal(0),
   setVal(1),
   setVal(1), 
 ]),
};

function setVal(trigger){
   return {value: (trigger = "0" ? "Apple" : "Microsoft"), triggerValue: trigger };
}