data-binding - Knockout.js 单选按钮的 boolean 数据绑定(bind)问题

标签 data-binding knockout.js boolean observable

我目前正在执行以下操作来弥补 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/

相关文章:

javascript - KnockoutJS 的 contenteditable 绑定(bind)

c# - 如何将字符串列表数据绑定(bind)到 WPF/WP7 中的 ListBox?

html - 想一次只显示列表中的 2 个名字,然后单击接下来的 2 个名字按钮,但有一个错误

javascript - JavaScript 中的最后一个 boolean 标志

javascript - 将 asp net linkbutton onclick 和 onclientclick 与 javascript 弹出窗口结合起来

javascript - 如何为默认 knockout 绑定(bind)创建包装函数

c# - 如何将 List<CustomObject> 绑定(bind)到 WPF DataGrid?

knockout.js - 有没有办法避免敲击时的提交绑定(bind)在按下回车键时发送表单?

knockout.js - 带 throttle 的 knockout 验证

c++ - 通过引用为 Bool 设置默认值