【问题标题】:Link 2 observable arrays together with knockout js将 2 个可观察数组与淘汰赛 js 链接在一起
【发布时间】:2012-04-13 03:14:20
【问题描述】:

我有 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 的回调?

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 2018-08-02
    相关资源
    最近更新 更多