how to implement checkbox dependencies in knockoutjs

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

by kougiland

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: "Behoerde" },
        { id: "Arzt" },
        { id: "Freizeit" },
        { id: "Arbeit" },
        { id: "Bildung" },
        { id: "Gericht" },
        { id: "Sonstiges" }
        ]);
    this.checked = ko.observableArray();
    this.checked.subscribe(function(newValue) {
        if (self.checked.indexOf("Arzt") > -1) {
            if (self.checked.indexOf("Bildung") < 0) {
               self.checked.push("Bildung");
            }  
            if (self.checked.indexOf("Sonstiges") < 0) {
               self.checked.push("Sonstiges");
            }  
        }
    });
    
    this.shouldBeDisabled = function(item) {
         return (item.id === "Sonstiges" || item.id ==="Bildung") && self.checked.indexOf("Arzt") > -1;     
    };
};

ko.applyBindings(new ViewModel());