2013-02-20 88 views
0

这与本主题中的其他问题类似,但不同。knockoutjs在取消选中一个或多个项目时取消选择/选中所有复选框

我有一个记录列表,每个记录都有一个select复选框。

在表头中我有一个“全选”复选框。

当用户选中/取消选中“全选”时,记录被选中/取消选中。这工作正常。

但是,当一个或多个记录被取消选择时,我需要取消选择我的“全选”复选框。

我的标记:

<table> 
    <thead> 
     <tr> 
      <th>Name</th> 
      <th><input type="checkbox" data-bind="checked: SelectAll" /></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: Selected" /></td> 
     </tr> 
    </tbody> 
</table> 

我的脚本(编辑):

function MasterViewModel() { 
    var self = this; 

    self.People = ko.observableArray(); 
    self.SelectAll = ko.observable(false); 

    self.SelectAll.subscribe(function (newValue) { 
     ko.utils.arrayForEach(self.People(), function (person) { 
      person.Selected(newValue); 
     }); 
    }); 
} 


my.Person = function (name, selected) { 
    var self = this; 

    self.Name = name; 
    self.Selected = ko.observable(false); 
} 

回答

6

这工作

http://jsfiddle.net/AneL9/

self.SelectAll = ko.computed({ 
    read: function() { 
     var item = ko.utils.arrayFirst(self.People(), function(item) { 
      return !item.Selected(); 
     }); 
     return item == null;   
    }, 
    write: function(value) { 
     ko.utils.arrayForEach(self.People(), function (person) { 
      person.Selected(value); 
     }); 
    } 
}); 

,但会给你一个欧尔N^2 proble m如果选择取消一切,你可以用计算来解决该

http://www.knockmeout.net/2011/04/pausing-notifications-in-knockoutjs.html

编辑pasuable:您还可以扩展计算与油门,这样你可以避免欧尔N^2问题

.extend({ throttle: 1 }) 

http://jsfiddle.net/AneL9/44/

+0

这就是现货。非常感谢你。 – Wazygoose 2013-02-20 14:20:25

+0

@Anders我使用没有“Selected”列的Json对象绑定数据。通过Json对象绑定数据时的任何替代方法? – seadrag0n 2014-07-21 14:34:34

+0

您需要创建一个ViewModel,用于保存数据旁边的信息。 – Anders 2014-07-21 16:03:31

1

你应该让SelectAll计算观察到的是这样的:

self.SelectAll = ko.computed({ 
    read: function() { 
     var persons = self.People(); 
     for (var i = 0, l = persons.length; i < l; i++) 
      if (!persons[i].Selected()) return false; 
     return true; 
    }, 
    write: function(value) { 
     ko.utils.arrayForEach(self.People(), function(person){ 
      person.Selected(value); 
     }); 
    } 
}); 

和strip SelectAll.subscribe out。

http://jsfiddle.net/Yqj59/

相关问题