使用knockout.js禁用单选按钮

时间:2011-08-29 22:55:13

标签: radio-button knockout.js

如何使用knockout.js禁用单选按钮?我不希望用户能够选择它。我的模板无效。

<div id="answers" data-bind="template: { name: 'answerTmpl', data: interactive.answers }">
    </div>

    <script id="answerTmpl" type="text/html">

        {{each(index, value) $data}}
        <div>
            <input type="radio" value="${index}" name="Answer" data-bind="disable: app.viewModel.avatars.speaking, checked: app.viewModel.interactive.answerSelected"/> <span>${value}</span> 
        </div>
        {{/each}}
    </script>

app.avatars.js

(function (app, $, undefined) {

    app.viewModel = app.viewModel || {};

    app.viewModel.avatars = {
        speaking: ko.observable(false),
        loaded: ko.observable(false)
    };

app.interactive.js

(function (app, $, undefined) {

    app.viewModel = app.viewModel || {};

    app.viewModel.interactive = {
        timeout: 1500,
        answers: ko.observableArray(),
        answerSelected: ko.observable(''),
        correctAnswer: ko.observable(-1),
        bookPage: ko.observable(1),
        chapterEmail: ko.observable(''),
        trialogue: {
            inProgress: ko.observable(false),
            response: ko.observable(''),
            conversation: ko.observableArray()
        }
    };

    app.interactive.init = function () {
         ko.applyBindings(app.viewModel);
    };

1 个答案:

答案 0 :(得分:3)

当您使用全局变量而不是绑定数据时,您似乎需要显式评估函数:http://jsfiddle.net/nFgnj/

<input type="radio" value="${index}" name="Answer" 
    data-bind="disable:app.viewModel.avatars.speaking(),
               checked:app.viewModel.interactive.answerSelected()" />

我真的不喜欢这个解决方案,因为它依赖app作为全局变量。