2014-09-03 31 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