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
      observable($.parseJSON(elementValue));
    };    // register change handler for element
    ko.utils.registerEventHandler(element,
                                  "change",
                                  changeHandler);
  },
  update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext)
  {
    var elementValue = $.parseJSON($(element).val());
    var observableValue = ko.utils.unwrapObservable(valueAccessor());    if (elementValue === observableValue)
    {
      element.checked = true;
    }
    else
    {
      element.checked = false;
    }
  }
};

In your HTML do following:

<input type="radio" name="yesno" value="true" data-bind="trueFalseRadioButton: YourObservableName" />
<label>Yes</label> 
<input type="radio" name="yesno" value="false" data-bind="trueFalseRadioButton: YourObservableName" />
<label>No</label>

And done.. simple!!. This enables a pair of radio button to have two way binding using knockout.

Hope that would help somebody.

Thanks...


Similar Articles