how to implement checkbox dependencies in knockoutjs

http://stackoverflow.com/questions/9228431/how-to-implement-checkbox-dependencies-in-knockoutjs

by rniemeyer

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.0.0.js"></script>
<ul data-bind="foreach: items">
    <li>
        <span data-bind="text: id"></span>
        <input type="checkbox" data-bind="attr: { value: id }, checked: $root.checked, disable: $root.shouldBeDisabled($data)" />
    </li>
</ul>

<hr/>

<div data-bind="text: ko.toJSON($root)"></div>

JavaScript

var ViewModel = function() {
    var self = this;
    this.items = ko.observableArray([
        { id: "A" },
        { id: "B" },
        { id: "C" },
        { id: "D" }
        ]);
    this.checked = ko.observableArray();
    this.checked.subscribe(function(newValue) {
        if (self.checked.indexOf("C") > -1) {
            if (self.checked.indexOf("A") < 0) {
               self.checked.push("A");
            }  
            if (self.checked.indexOf("B") < 0) {
               self.checked.push("B");
            }  
        }
    });
    
    this.shouldBeDisabled = function(item) {
         return (item.id === "B" || item.id ==="A") && self.checked.indexOf("C") > -1;     
    };
};

ko.applyBindings(new ViewModel());