Binding true / false to radio buttons in Knockout JS

http://stackoverflow.com/questions/10127001/binding-true-false-to-radio-buttons-in-knockout-js

by rniemeyer

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<label>Male
   <input type="radio" name="IsMale" value="true" data-bind="checkedRadioToBool: IsMale"/>
</label> 
<label>Female
   <input type="radio" name="IsMale" value="false" data-bind="checkedRadioToBool: IsMale"/>
</label>

<hr/>

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

CSS

li { margin: 5px; background: #eee; height: 50px; }

.menu { position: absolute; background-color: #000; color: #fff; height: 100px; }

JavaScript

ko.bindingHandlers.checkedRadioToBool = {
    init: function(element, valueAccessor, allBindingsAccessor) {
        var observable = valueAccessor(),
            interceptor = ko.computed({
                read: function() {
                    return observable().toString();  
                },
                write: function(newValue) {
                     observable(newValue === "true");
                },
                owner: this   
            });
        ko.applyBindingsToNode(element, { checked: interceptor });     
    }
};

var ViewModel = function() {
   this.IsMale = ko.observable(true);       
};

ko.applyBindings(new ViewModel());