2012-04-10 156 views
1

我有2個數組。一個是一個地區所有學校的陣列,另一個是這些學校所有學生的名單。學生對象包含他們所屬的學校。我可以列出所有學校的名單,我可以列出所有學生的名單。我希望能夠選擇一所學校(或幾所學校),並讓學生名單隻顯示該學校的學生。鏈接2可觀察陣列與淘汰賽js

這裏是我有(在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回調?

回答

2

我建議將selected_players_to_teams作爲ko.computed實施,在selected_schools更新時運行,並返回selected_schools的players_to_teams。

看到這個的jsfiddle一個唯一的代碼,例如:http://jsfiddle.net/MqNPm/

+2

我開始回答時@Tuan回答。這是我的小提琴,如果它有幫助:http://jsfiddle.net/rniemeyer/Getfx/ – 2012-04-10 18:40:24