开发者

Deselecting radio buttons while keeping the View Model in synch

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?

My view code:

<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>

Corresponding 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);

An example can be viewed here online in this fiddle.


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);   
    }
});

Updated Fiddle


You don't need to worry about the checked attribute, that's done for you. Change your event to this:

$('#test input[type="radio"]').click(function (event) {

    var checked = $(this).hasClass('checked');
    if (checked) {
        $(this).removeClass('checked');
    }
    else {
        $(this).addClass('checked');
    }
});

Fork of your fiddle here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜