我目前正在执行以下操作来弥补 boolean 值不能很好地映射到单选按钮的问题。由于从可观察值中读取字段的方式,我陷入了将 1 和 0 绑定(bind)到值(而不是 true 和 false)的困境。 Pref1/Pref2 的值作为来自服务器的 true/false boolean 值。这里的关键是我不仅希望对单选按钮的选中值进行数据绑定(bind)以匹配对象中的 true/false,而且还希望将 true/false 的 boolean 值写回到 GraduationClass 对象中。我的补偿代码不仅丑陋,而且不可扩展。
<input type="radio" value="1" name="radioGroup" data-bind="checked: Pref1" />Yes
<input type="radio" value="0" name="radioGroup" data-bind="checked: Pref2" />No
<a href="javascript:void(0);" data-bind="click: $root.saveGraduationClass ">Save</a>
function SiteSettingsViewModel() {
var self = this;
this.saveGraduationClass = function(graduationClass) {
// hack until i get a custom radio button binding
if (graduationClass.Pref1() == 1) {
graduationClass.Pref1(true);
} else {
graduationClass.Pref1(false);
}
if (graduationClass.Pref2() == 1) {
graduationClass.Pref2(true);
} else {
graduationClass.Pref2(false);
}
// ...ajax call to save graduationClass to the server
}
function GraduationClass(data) {
var self = this;
ko.mapping.fromJS(data, {}, this);
}
最佳答案
这是来自 KnockoutJs 网站的示例,演示了如何使用单选按钮 “检查”属性:
<p>Send me spam: <input type="checkbox" data-bind="checked: wantsSpam" /></p>
<div data-bind="visible: wantsSpam">
Preferred flavor of spam:
<div><input type="radio" name="flavorGroup" value="cherry" data-bind="checked: spamFlavor" /> Cherry</div>
<div><input type="radio" name="flavorGroup" value="almond" data-bind="checked: spamFlavor" /> Almond</div>
<div><input type="radio" name="flavorGroup" value="msg" data-bind="checked: spamFlavor" /> Monosodium Glutamate</div>
</div>
<script type="text/javascript">
var viewModel = {
wantsSpam: ko.observable(true),
spamFlavor: ko.observable("almond") // Initially selects only the Almond radio button
};
// ... then later ...
viewModel.spamFlavor("msg"); // Now only Monosodium Glutamate is checked
</script>
但我不明白为什么你在一个单选按钮组“radioGroup”中使用两个对象 - “Pref1”和“Pref2”?在这种情况下,您只能使用一个对象,如示例中使用的“spamFlavor”。
所以,请更详细地描述您想要绑定(bind)的内容:一个单选按钮按一个选定的值分组,或者其他东西。
您还可以使用计算的可观察量来计算不同的值,请参阅 example .
关于data-binding - Knockout.js 单选按钮的 boolean 数据绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10972741/