あなたのフィドルは、古いバージョンのノックアウト(2.0)を使用しています。ノックアウトの3.xバージョンで導入されたchecked
bindingを使用することができます。
<input
type="radio"
name="uniqueQuestionName"
data-bind="checkedValue: $data,
click: $root.setCorrectAnswer,
checked: $root.correctAnswer"
/>
デモ:
function Question() {
var self = this;
this.name = "My Question";
var i = 0;
this.answers = ko.observableArray([
new Answer(++i, "Answer 1", false),
new Answer(++i, "Answer 2", true),
new Answer(++i, "Answer 3", false)
]);
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);
}
var question = new Question();
//Set default correct answer just for example
question.correctAnswer(question.answers()[1]);
ko.applyBindings(question);
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<div data-bind="text:name"></div>
<div data-bind="foreach:answers">
<label>
<span data-bind="text: name"></span>
<input type="radio" name="uniqueQuestionName" data-bind="checkedValue: $data,
click: $root.setCorrectAnswer,
checked: $root.correctAnswer" />
</label>
<br />
</div>
<hr/>
<pre data-bind="text: JSON.stringify(ko.toJS($root), null, 2)"></pre>
だけ
checked
$root.correctAnswer
への結合を設定します