Knockout Two way binding radio button to an Observable

I was working on a project where a requirement was to bind a yes/no radio button pair to a boolean observable; but while implementing found that knockout's two way "data-bind" do not play nicely with boolean type observables. 

The solution lies in JQuery's "Custom Handler", present to you the simple, clean and yet effective approach:
Have a custom handler as follows:
/// ----------------------------------------------------------------------- /// This binding is used to bind a pair of radio buttons to a boolean observable
ko.bindingHandlers.trueFalseRadioButton =
  init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext)
    // event handler for the element change event
    var changeHandler = function ()
      var elementValue = $(element).val();
      var observable = valueAccessor();      // set the observable value to the boolean value of the element value
    };    // register change handler for element
  update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext)
    var elementValue = $.parseJSON($(element).val());
    var observableValue = ko.utils.unwrapObservable(valueAccessor());    if (elementValue === observableValue)
      element.checked = true;
      element.checked = false;

In your html do following:
<input type="radio" name="yesno" value="true" data-bind="trueFalseRadioButton: YourObservableName" />
<input type="radio" name="yesno" value="false" data-bind="trueFalseRadioButton: YourObservableName" />

And done.. simple!!. T
his enables a pair of radio button to have two way binding using knockout.
Hope that would help somebody.

Up Next
    Ebook Download
    View all
    View all