2014-09-03 60 views
1

我想選擇所有使用淘汰賽的複選框。這裏是我的視圖模型使用淘汰賽選擇所有複選框

function MasterViewModel() { 
var self = this; 
self.People = ko.observableArray([new Person("Test1", false), new Person("Test2", false)]); 
self.selectedAllBox = ko.observable(false); 

self.selectedAllBox.subscribe(function (newValue) { 
    if (newValue == true) { 
     ko.utils.arrayForEach(self.People(), function (item) { 
      item.sel = true; 
     }); 
    } else { 
     ko.utils.arrayForEach(self.People(), function (item) { 
      item.sel = false; 

     }); 
    } 
}); 

} 
Person = function (name, sel) { 
this.Name = name; 
this.sel = sel; 
} 

ko.applyBindings(new MasterViewModel()); 

這是我的看法

<table> 
<thead> 
    <tr> 
     <th>Name</th> 
     <th> 
      <input type="checkbox" data-bind="checked: selectedAllBox" /> 
     </th> 
    </tr> 
</thead> 
<tbody data-bind="foreach: $data.People"> 
    <tr> 
     <td data-bind="text: Name"></td> 
     <td class="center"> 
      <input type="checkbox" data-bind="checked: sel" /> 
     </td> 
    </tr> 
</tbody></table> 

我不能讓它檢查所有。這是我的Fiddle。你能告訴我我做錯了什麼嗎?

回答

2

你需要讓內部Personsel屬性觀察到:

Person = function (name, sel) { 
    this.Name = name; 
    this.sel = ko.observable(sel); 
} 

而且你需要設置觀察到的int selectedAllBox.subscribe

self.selectedAllBox.subscribe(function (newValue) { 
    if (newValue == true) { 
     ko.utils.arrayForEach(self.People(), function (item) { 
      item.sel(true); 
     }); 
    } else { 
     ko.utils.arrayForEach(self.People(), function (item) { 
      item.sel(false); 

     }); 
    } 
}); 

演示JSFiddle

+0

我知道,我可以使它可觀察,但我不能,因爲我從其他地方得到這個數據 – Happy 2014-09-03 09:15:29

+0

那麼你需要創建一個包裝一個人,並具有可觀測proeprties viewmodel。它不會與可觀察的屬性一起工作。 – nemesv 2014-09-03 09:19:32

+0

如何包裝它?我嘗試使用someObservableArray(self.People),但沒有工作 – Happy 2014-09-03 09:20:47