2

我有 2 个数组。一个是一个地区所有学校的数组,另一个是这些学校所有学生的列表。学生对象包含知道他们属于哪个学校。我可以列出所有学校,也可以列出所有学生。我希望能够选择一所学校(或几所学校)并让学生列表仅显示该学校的学生。

这是我得到的(在 CoffeeScript 中):

ViewModel = () ->
    @accounts = ko.observableArray([])
    @players_to_teams = ko.observableArray([])
    @selected_players_to_teams = ko.observableArray([])
    @selected_schools = ko.observableArray([])
    null

看法:

<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>

更改时selected_schools,我需要更新selected_players_to_teams以仅包含selected_schools数组中有学校的学生记录吗?

有没有办法链接 observableArrays,使 observableArrays 成为一个函数,或者可能捕获 observableArray 的回调?

4

1 回答 1

2

我建议将 selected_players_to_teams 实现为在 selected_schools 更新时运行的 ko.computed,并返回 selected_schools 的 player_to_teams。

有关仅代码示例,请参见此 jsfiddle:http: //jsfiddle.net/MqNPm/

于 2012-04-10T18:31:52.257 回答