How to bind a checkbox to the inverse of a value

http://stackoverflow.com/questions/8902608/how-to-bind-a-checkbox-to-the-inverse-of-a-value

by rniemeyer

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.0.0.js"></script>
<input type="checkbox" data-bind="inverseChecked: needsReview"> Not Required 
<input type="checkbox" data-bind="checked: needsReview" /> Needs Review
<br>
<div id="Some related text" data-bind="visible: needsReview"> needs review info </div>
<div id="Some related text" data-bind="visible: !needsReview()"> does not need review info </div>
<hr/>
<div data-bind="text: ko.toJSON($data)"></div>

JavaScript

ko.bindingHandlers.inverseChecked = {
    init: function(element, valueAccessor, allBindingsAccessor) {
        var value = valueAccessor();
        var interceptor = ko.computed({
                            read: function() {
                                return !value();
                            },
                            write: function(newValue) {
                                value(!newValue);
                            },
                            disposeWhenNodeIsRemoved: element
                        }); 
        
        var newValueAccessor = function() { return interceptor; };
            
        
        //keep a reference, so we can use in update function
        ko.utils.domData.set(element, "newValueAccessor", newValueAccessor);
        //call the real checked binding's init with the interceptor instead of our real observable
        ko.bindingHandlers.checked.init(element, newValueAccessor, allBindingsAccessor);
    },
    update: function(element, valueAccessor) {
        //call the real checked binding's update with our interceptor instead of our real observable
        ko.bindingHandlers.checked.update(element, ko.utils.domData.get(element, "newValueAccessor"));  
    }
};

var viewModel = {
    needsReview: ko.observable(true),
    toggleNeedsReview: function() {
         this.needsReview(!this.needsReview()); 
    }
};

ko.applyBindings(viewModel);