Rod
Rod

Reputation: 15423

for each with 2 observable collections

I have a teams and rank scoring collection to track, say a relay race.

So as a user enter teams into collection, each team will be awarded points based on ranking.

https://jsfiddle.net/2ae3dv8d/

<strong>Teams:</strong>
<!-- ko foreach: teams -->
<div>
    <input type="text" data-bind="value: name" />
</div>
<!-- /ko -->


function Team(name)
{
  var self = this;
  self.name = name'
}

function RankScoring(label, points){
  var self = this;
  self.label = label;
  self.points = points;
}

function AppViewModel()
{
  var self = this;
  self.teams = ko.observableArray([
    new Team('red'),
    new Team('blue')
  ]);
  self.rankscoring = ko.observableArray([
    new RankScoring('1st', ''),
    new RankScoring('2nd', ''),
    new RankScoring('3rd', ''),
  ]);
}

In this particular example, let's say the game had 2 teams. So, I'm only going to need to use 2 items from RankScoring collection based on the number of teams involved. How do I data-bind RankScoring collection so user can enter points for rankings? And I welcome suggestions for easier way to accomplish the idea.

**Teams:**
Red
Blue

**Scoring**
1st place - 10
2nd place - 5

Upvotes: 0

Views: 35

Answers (1)

Travis Schettler
Travis Schettler

Reputation: 854

Add a computed to show textboxes for available ranks:

self.availablerankscoring = ko.computed(function(){
    return self.rankscoring().slice(0,self.teams().length);
});

Add another foreach for available ranks:

<!-- ko foreach: availablerankscoring -->
<div>
    <label data-bind="text: label"></label><input type="text" data-bind="value: points" />
</div>
<!-- /ko -->

Fiddle

Upvotes: 1

Related Questions