Binding KnockoutJS to Radio Button with computed

http://stackoverflow.com/questions/10283580/binding-knockoutjs-to-radio-button-with-computed

by kougiland

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.0.0.debug.js"></script>
<div>Wiederholung</div>
<div data-bind="foreach:answers">
        <label>
            <input type="radio" name="wiederholung" data-bind="value: $data.name, checked: $root.defaultChecked, click: $root.setChosenAnswer" />
            <span data-bind="text: name"></span>
        </label>
        <br />
</div>
<pre data-bind="text: JSON.stringify(ko.toJS($root), null, 2)"></pre>

CSS

pre{
    background:black;
    color:green; 
    padding:20px;
    margin-top:20px;
}

JavaScript

function Question() {
    var self = this;
    this.answers = ko.observableArray([
        new Answer("Nie", true),
        new Answer("Täglich", false),
        new Answer("Wöchentlich", false)]);

    this.setChosenAnswer = function(wahl) {
        if (wahl !== self.userAnswer()) {
            ko.utils.arrayForEach(self.answers(), function(answer)  {
                answer.isChosen(wahl === answer); 
            });
       
            self.userAnswer(wahl);           
        }
        return true;
    };
    
    this.userAnswer = ko.observable();
    this.defaultChecked = "Nie";
    this.userAnswer.subscribe(function(newValue) {
        alert("Ich moechte mein Termin " + this.userAnswer().name() + " Wiederholen");
    }, this);
}

        
function Answer(name, isChosen) {
    this.name = ko.observable(name);
    this.isChosen = ko.observable(isChosen);
}

ko.applyBindings(new Question());