Binding KnockoutJS to Radio Button with computed
http://stackoverflow.com/questions/10283580/binding-knockoutjs-to-radio-button-with-computed
HTML
<script src="http://knockoutjs.com/downloads/knockout-2.0.0.debug.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script>
<div data-bind="text:name"></div>
<div data-bind="foreach:answers.options()">
<label> <span data-bind="text: name"></span>
<input type="radio" name="uniqueQuestionName" data-bind="click: selectedTime.bind($data)" />
</label>
<br />
</div>
<hr/>
<pre data-bind="text: JSON.stringify($root, null, 2)"></pre>
JavaScript
function Question() {
var self = this;
this.name = "Mandag";
var i = 0;
this.answers = ko.mapping.fromJS({
options: [{
name: "SFO",
isRight: false,
selectedTime: function (item) {
alert("item1");
}
}, {
name: "Skole",
isRight: false,
selectedTime: function (item) {
alert("item2");
}
}]
});
this.setCorrectAnswer = function (correct) {
if (correct !== self.correctAnswer()) {
ko.utils.arrayForEach(self.answers(), function (answer) {
answer.isRight(correct === answer);
});
self.correctAnswer(correct);
}
return true;
};
this.correctAnswer = ko.observable();
this.correctAnswer.subscribe(function (newValue) {
alert("The correct answer to " + this.name + " is now " + this.correctAnswer().name());
}, this);
}
function Answer(id, name, isRight) {
this.id = ko.observable(id);
this.name = ko.observable(name);
this.isRight = ko.observable(isRight);
}
debugger;
var vm = new Question();
ko.applyBindings(vm);