我认为您遇到了一个已在更高版本的淘汰赛中修复的错误。
它应该工作的方式(和你尝试过的一样):
<input name="Test" type="radio" data-bind="checkedValue: true,
checked: isBlue" />Blue
<input name="Test" type="radio" data-bind="checkedValue: false,
checked: isBlue" />No Blue
ko.applyBindings({
isBlue: ko.observable(false)
});
如果您包含淘汰赛版本 3.4,它会按预期工作:
ko.applyBindings({
isBlue: ko.observable(false)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<label>
<input name="Test" type="radio" data-bind="checkedValue: true, checked: isBlue" /> Blue
</label>
<label>
<input name="Test" type="radio" data-bind="checkedValue: false, checked: isBlue" /> No Blue
</label>
<br />
<strong style="color: green">3.4.0: Does work</strong>
当您包含您在小提琴中使用的版本(2.1.0)时,它不会:
ko.applyBindings({
isBlue: ko.observable(false)
});
<script src="https://cloud.github.com/downloads/knockout/knockout/knockout-2.1.0.js"></script>
<label>
<input name="Test" type="radio" data-bind="checkedValue: true, checked: isBlue" />Blue
</label>
<label>
<input name="Test" type="radio" data-bind="checkedValue: false, checked: isBlue" />No Blue
</label>
<br />
<strong style="color: red">2.1.0: Does not work</strong>
编辑:经过更多挖掘:我认为这不是 2.1.0 中的错误; checkedValue 那时甚至都不存在!
查看源代码,您会注意到获取检查值的逻辑在 2.1.0 和更高版本之间非常不同:
在 2.1.0 中:
if (element.type == "checkbox") {
valueToWrite = element.checked;
} else if ((element.type == "radio") && (element.checked)) {
valueToWrite = element.value;
}
在 3.4.0 中:
var checkedValue = ko.pureComputed(function() {
// Treat "value" like "checkedValue" when it is included with "checked" binding
if (allBindings['has']('checkedValue')) {
return ko.utils.unwrapObservable(allBindings.get('checkedValue'));
} else if (allBindings['has']('value')) {
return ko.utils.unwrapObservable(allBindings.get('value'));
}
return element.value;
});
所以一个明确的答案是:更新到 3.4.0,或者创建一个自定义的检查绑定来实现 3.4.0 的行为(如果版本更新会破坏你的项目)