KnockoutJS单选按钮检查绑定与JQuery Mobile 1.4一起使用?

时间:2014-10-16 03:20:59

标签: jquery-mobile knockout.js

我一直在尝试研究如何使用检查绑定与Knockout和JQuery Mobile一起使用。出于某种原因,vanilla Knockout JS“检查”绑定不起作用:

<fieldset data-role="controlgroup">
    <legend>Your favorite flavor:legend>
    <input type="radio" name="flavor-selection" value="Chocolate" id="flavor-selection-chocolate" data-bind="checked: flavor" />
    <label for="flavor-selection-chocolate">Normal</label>
    <input type="radio" name="flavor-selection" value="Vanilla" id="flavor-selection-vanilla" data-bind="checked: flavor" />
    <label for="flavor-selection-vanilla">Party</label>
</fieldset>

任何想法为什么?

1 个答案:

答案 0 :(得分:1)

事实证明,jQuery Mobile为单选按钮设置了标签,以显示无线电选择(隐藏实际的单选按钮本身)。

我尝试了这里找到的建议:http://codeclimber.net.nz/archive/2013/08/16/How-to-bind-a-jquery-mobile-radio-button-list-to.aspx但是没有取得任何成功 - 我怀疑它可能只适用于以前版本的jQuery Mobile。

这是我的替代选择:

创建一个自定义绑定,根据隐藏复选框的选中状态切换标签上的“ui-radio-on”和“ui-radio-off”类:

ko.bindingHandlers.jqMobileRadioChecked = {
    init: function (element, valueAccessor, allBindingsAccessor, data, context) {
        ko.bindingHandlers.checked.init(element, valueAccessor, allBindingsAccessor, data, context);
    },
    update: function (element, valueAccessor, allBindingsAccessor, data, context) {

        var viewModelValue = valueAccessor();
        var viewModelValueUnwrapped = ko.unwrap(viewModelValue);

        var $el = $(element);
        var $label = $el.siblings("label[for='" + $el.attr("id") + "']");
        if (viewModelValueUnwrapped === $el.val()) {
            $label.removeClass("ui-radio-off");
            $label.addClass("ui-radio-on");
        } else {
            $label.removeClass("ui-radio-on");
            $label.addClass("ui-radio-off");
        }
    }
};

然后HTML变成:

<fieldset data-role="controlgroup">
    <legend>Your favorite flavor:legend>
    <input type="radio" name="flavor-selection" value="Chocolate" id="flavor-selection-chocolate" data-bind="jqMobileRadioChecked: flavor" />
    <label for="flavor-selection-chocolate">Normal</label>
    <input type="radio" name="flavor-selection" value="Vanilla" id="flavor-selection-vanilla" data-bind="jqMobileRadioChecked: flavor" />
    <label for="flavor-selection-vanilla">Party</label>
</fieldset>