1
votes

I have set a custom binding for input type radio, which is like this:

"radio-yesno": function(bindingContext, dataClasses){
    return {
        click: this,
    }
},

The Html Input Type Radio binds to this is written like this:

<label class="radio inline">
   <input type="radio" name="RadioTest" id="RadioYes" data-class="radio-yesno"/>
   Yes
</label>
<label class="radio inline">
   <input type="radio" name="RadioTest" id="RadioNo" data-class="radio-yesno"/>
   No
</label>

(You may notice that I am using data-class here to bind the element, it is because I am using the ClassBindingProvider plugin)

The problem now is when the radio button is clicked, the function which contains the associated observable of this element is actually triggered and during debugging it can be seen that the value of

$('#RadioNo').is(':checked')

is actually true when the No Radio Button is clicked and is false when the Yes Radio Button is clicked. BUT, the page itself doesn't show the Radio Button to be selected (checked).

Currently the ko BindingHandlers that I am using here is "click" only.

I have tried to add more bindingHandler which is "checked: this" and put it below the "click: this" line, but still doesn't work.

Could someone please help me to identify what is the problem here and how should it be fixed?

Thanks.

1

1 Answers

1
votes

It's not clear from your question exactly what you want the behavior to be, but I've put together a snippet with typical radio button behavior. The most important change is that I added a value attribute to each radio button element. Without them, there's no value change on selecting a different radio button.

I have written but commented out a click binding here, and am using a checked binding, which is usually the better way to bind a radio group. I subscribe to the bound variable just to output information when it changes.

let bindings = {
  "radio-yesno": function(bindingContext, dataClasses) {
    return {
      // click: this.clickHandler,
      checked: this.checkedVariable
    }
  }
};
ko.bindingProvider.instance = new ko.classBindingProvider(bindings);
let vm = {
  clickHandler: function(data, event) {
    console.debug("Click:", data, event);
    true;
  },
  checkedVariable: ko.observable('on')
};

vm.checkedVariable.subscribe((newValue) => {
  console.debug('New value:', newValue);
});

ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="//rawgit.com/rniemeyer/knockout-classBindingProvider/master/src/knockout-classBindingProvider.js"></script>
<label class="radio inline">
  <input type="radio" name="RadioTest" value="on" data-class="radio-yesno" />Yes
</label>
<label class="radio inline">
  <input type="radio" name="RadioTest" value="off" data-class="radio-yesno" />No
</label>