這裏是你將如何去限制你的複選框選中計數:
Link to a fiddle for this
// Describes what an option is
var option = function(data){
this.Name = ko.observable(data.Name);
this.Selected = ko.observable(data.Selected);
}
var optionsVM = function(){
var self = this;
// Collection of options
self.options = ko.observableArray();
// Find out which items are selected
self.selectedItems = ko.computed(function(){
return ko.utils.arrayFilter(self.options(), function(item){
return item.Selected() === true;
});
});
// Dummy init to put options in the collection
self.init = function(){
self.options([
new option({ Name : "Test 0", Selected: false }),
new option({ Name : "Test 1", Selected: false }),
new option({ Name : "Test 2", Selected: false }),
new option({ Name : "Test 3", Selected: false }),
new option({ Name : "Test 4", Selected: false })
])
};
self.canCheck = function(item){
var _canCheck = self.selectedItems().length < 2;
if (_canCheck){
// If it can check then just toggle
item.Selected(!item.Selected());
return true;
}
if (!_canCheck && item.Selected()){
// if it can't then only allow deselection
item.Selected(false);
return true;
}
}
}
var myOptions = new optionsVM();
myOptions.init();
ko.applyBindings(myOptions);
HTML:
<ul data-bind="foreach: options">
<li><label><input type="checkbox" data-bind="click: $parent.canCheck, checked: Selected()" /> <span data-bind="text: Name"></span> <span data-bind="text: Selected"></span></label></li>
</ul>
<p data-bind="text: selectedItems().length"></p>
密切關注這樣的事實,我所做的檢查通過在視圖中使用()
0在複選框中綁定單向綁定(只讀屬性)
有很多方法可以做到這一點,這只是一個。