Reputation: 23576
I have 2 arrays. One is an array of all schools in an area, the other is a list of all students at those schools. The student objects contain know which school they belong to. I can make a list of all the schools and I can make a list of all the students. I'd like to be able to select a school (or a couple schools) and have the list of students only show students from that school.
Here's what I've got (in CoffeeScript):
ViewModel = () ->
@accounts = ko.observableArray([])
@players_to_teams = ko.observableArray([])
@selected_players_to_teams = ko.observableArray([])
@selected_schools = ko.observableArray([])
null
View:
<label for="school_selection">School</label>
<select id="school_selection" class="inline" multiple=true size="50" data-bind="options:accounts, optionsText: 'Name', selectedOptions: selected_schools"></select>
<div id="player_list" class="inline">
<table class="table table-striped">
<thead>
<tr>
<th id="firstName">First Name</th>
<th id="lastName">Last Name</th>
<th id="position">Position</th>
<th id="teamName">Team Name</th>
<th id="accountId">Account ID</th>
</tr>
</thead>
<tbody data-bind="foreach: selected_players_to_teams">
<tr>
<td data-bind="text: FirstName"></td>
<td data-bind="text: LastName"></td>
</tr>
</tbody>
</table>
</div>
When selected_schools
changes, I need to update selected_players_to_teams
to only contain the student records that have schools in the selected_schools
array?
Is there a way to link observableArrays, make observableArrays a function, or maybe catch a call back for an observableArray?
Upvotes: 2
Views: 976
Reputation: 5412
I suggest implementing selected_players_to_teams as a ko.computed that runs when selected_schools is updated, and returns the players_to_teams for the selected_schools.
See this jsfiddle for a code-only example: http://jsfiddle.net/MqNPm/
Tuan
Upvotes: 2