通过$ parent绑定绑定单选按钮

时间:2012-04-24 02:43:29

标签: javascript knockout.js

我正在foreach循环中生成单选按钮。我正在尝试将checked属性绑定到父级中的基本observable。不幸的是,单击单选按钮时,单击处理程序中的父属性似乎不会更新。

基于某些previous work,点击处理程序似乎应该是一个可以在视图模型上获取更新值的可接受位置。最奇怪的是,似乎在您点击单选按钮几次后,正确的值开始出现。

Full Fiddle

代码:

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>​

2 个答案:

答案 0 :(得分:0)

当您将选中的值绑定到$ parent.correctAnswer时,它是双向绑定,这意味着您将正确答案更新为您单击的任何内容。

我建议用以下内容替换它:

checked:$parent.isCorrectAnswer()

这是一个ko.computed,它总能返回正确答案,但也可以在所选值发生变化时提醒您

this.isCorrectAnswer= ko.computed(function () {        
    alert('your message');
    return 2;//return correct answer
});

代码未经测试并提供给您:)

答案 1 :(得分:0)

更改

answerId === correctAnswer

answerId == correctAnswer

每次都能正常工作。

希望这有帮助!