使用KnockoutJS禁用复选框

时间:2014-08-25 22:31:23

标签: knockout.js knockout-2.0 knockout-mapping-plugin knockout-validation knockout-mvc

当可观察数组的长度达到特定限制时,我无法禁用该复选框。 以下是代码链接:http://jsfiddle.net/pLNdc/59/

<ul class="options" data-bind="foreach: choices">
<li><label><input type="checkbox" name="NotifyMembers"
    data-bind="attr: { value: $data },
               checked: $parent.selectedChoices,
               enable: $parent.selectedChoices.length < 2" />
    <span data-bind="text: $data"></span></label></li>
</ul>
<hr />

var viewModel = {};

viewModel.choices = ["one", "two", "three", "four", "five"];
viewModel.selectedChoices = ko.observableArray(["two", "four"]);

viewModel.selectedChoicesDelimited = ko.dependentObservable(function () {
    return viewModel.selectedChoices().join(",");
});

ko.applyBindings(viewModel);

感谢。

1 个答案:

答案 0 :(得分:3)

由于selectedChoices是一个可观察的,你需要在访问它的length属性之前用parens调用它,如下所示:

<input type="checkbox" name="NotifyMembers"
       data-bind="attr: { value: $data },
                  checked: $parent.selectedChoices,
                  enable: $parent.selectedChoices().length < 2" />