Knockout 和 jQuery Mobile:复选框 [英] Knockout and jQuery Mobile: Checkboxes

查看:23
本文介绍了Knockout 和 jQuery Mobile:复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向文档动态添加复选框和标签元素.Checkbox 元素具有 Knockout 的 data-bind 属性,可将其值绑定到 ViewModel 中的可观察值.但是,当我尝试通过执行

I'm trying to dynamically add checkbox and label elements to the document. Checkbox element has Knockout's data-bind attribute to bind its value to an observable value in the ViewModel. However when I try to style the checkboxes with jQuery Mobile by executing

$('input[type="checkbox"]').checkboxradio();

数据绑定属性将被删除.如果我省略上一行,数据绑定属性会正确设置并且绑定有效.

data-bind attributes will be removed. If I leave out the above line, data-bind attributes are properly set and the binding works.

有没有办法同时拥有 jQuery Mobile 样式和 Knockout 绑定?

Is there a way to have both jQuery Mobile styling and Knockout bindings at the same time?

我使用的是 jQuery Mobile RC1 和 Knockout 1.2.1.

I'm using jQuery Mobile RC1 and Knockout 1.2.1.

推荐答案

我也遇到过这个问题.不幸的是,这里的所有建议要么对我不起作用,要么有其他问题.所以我创建了一个简单的自定义绑定,适用于所有版本的 KO(包括最新的 v3):

I have also encountered this problem. Unfortunately, all the suggestions here either did not work for me or had other issues. So I have created a simple custom binding that works in all versions of KO (including the latest v3):

ko.bindingHandlers.jqmChecked = {
    init: ko.bindingHandlers.checked.init,
    update: function (element, valueAccessor) {
        //KO v3 and previous versions of KO handle this differently
        //KO v3 does not use 'update' for 'checked' binding
        if (ko.bindingHandlers.checked.update) 
            ko.bindingHandlers.checked.update.apply(this, arguments); //for KO < v3, delegate the call
        else 
            ko.utils.unwrapObservable(valueAccessor()); //for KO v3, force a subscription to get further updates

        if ($(element).data("mobile-checkboxradio")) //calling 'refresh' only if already enhanced by JQM
            $(element).checkboxradio('refresh');
    }
};

应该这样使用:

<input type="checkbox" data-bind="jqmChecked: someValue" id="checkbox1"/>

在此处查看完整的工作示例:

See a complete working example here:

http://jsfiddle.net/srgstm/ub6sq/

这篇关于Knockout 和 jQuery Mobile:复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆