我正在foreach
循环生成单选按钮。我正在尝试将选中的属性绑定到父级中的基本 observable。不幸的是,当单击单选按钮时,单击处理程序中似乎没有更新父属性。
根据之前的一些工作,似乎点击处理程序应该是在视图模型上获取更新值的可接受位置。最奇怪的是,在您单击单选按钮几次之后,似乎开始出现正确的值。
代码:
function Question() {
this.name = "My Question";
this.answers = ko.observableArray([
new Answer(1, "Answer 1", false),
new Answer(2, "Answer 2", true),
new Answer(3, "Answer 3", false)]);
this.correctAnswer = ko.observable(2);
}
function Answer(id, name, isRight) {
this.id = ko.observable(id);
this.name = ko.observable(name);
this.isRight = ko.observable(isRight);
}
ko.applyBindings(new Question());
$(document).on("click", "input[type='radio']", function () {
var answer = ko.dataFor(this);
var question = ko.contextFor(this).$parent;
var answerId = answer.id();
var correctAnswer = question.correctAnswer();
alert(answerId + " should equal " + correctAnswer +
(answerId === correctAnswer ? " SWEET" : " DAMNIT"));
});
HTML
<div data-bind="text:name"></div>
<div data-bind="foreach:answers">
<label>
<span data-bind="text: name"></span>
<input type="radio" name="X" data-bind="value: id, checked:$parent.correctAnswer" />
</label>
<br />
</div>