在保持视图模型同步的同时取消选择单选按钮 [英] Deselecting radio buttons while keeping the View Model in synch

查看:70
本文介绍了在保持视图模型同步的同时取消选择单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个广播组,允许用户(使用jQuery事件)取消选择以前的选择。我正在尝试添加KnockoutJS来跟踪更改,但是viewmodal与UI不同步。任何人都可以建议我如何让两者同步?

I have a radio group that allows the user (using jQuery events) to deselect previous selections. I am trying to add KnockoutJS to track changes, but the viewmodal gets out of sync with the UI. Can anyone suggest how I might get the two to be in sync?

我的观看代码:

<div id='test'>
    <input data-bind="checked: asd"  name='asd' type='radio' value="a"/>
    <input data-bind="checked: asd"  name='asd' type='radio' value="b"/>
    <input data-bind="checked: asd"  name='asd' type='radio' value="c"/>
</div>
<div>
     <p>Linked Value: <span data-bind="text: asd"></p>  
</div>

相应的JS:

$('#test input[type="radio"]').click(function (event) {
    var checked = $(this).hasClass('checked');
    if (checked) {
        $(this).removeAttr('checked');
        $(this).removeClass('checked');
    }
    else {
        $(this).addClass('checked');
    }
});

var viewModel = {
  asd: ko.observable("a")
};

ko.applyBindings(viewModel);

可以在这个小提琴

推荐答案

我认为一个简单的方法会要这样做:

I think that a simple way would be to do:

$('#test input[type="radio"]').click(function (event) {
    if ($(this).val() === viewModel.asd()) {
         viewModel.asd(null);   
    }
});

更新小提琴

这篇关于在保持视图模型同步的同时取消选择单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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