kingdango
kingdango

Reputation: 3999

How do you bind a bool value to a radio button using the Checked binding with Knockout?

Given the following JSON object, mapped using ko.mapping:

{ AllowNotifications: ko.observable(true) }

I want to bind a bool value to a radio button so that if True one radio is Checked, if False then the other is checked.

<input data-bind="checked: AllowNotifications" type="radio" name="allowNotifications" value="true"><label class="small positive" for="objectNotifications_true">Yes</label>
<input data-bind="checked: AllowNotifications" type="radio" name="allowNotifications" value="false"><label class="small negative" for="objectNotifications_false">No</label>

Presently this does not properly bind though no error is thrown. Why is this not working?

Upvotes: 1

Views: 2130

Answers (1)

kingdango
kingdango

Reputation: 3999

The reason the binding is not working is because the radio's value "true" or "false" is a string and Knockout is trying to bind to the literal bool value.

A reasonable workaround is to instruct Knockout to translate the bool values true and false to string representations. To do so we must provide some instructions when we map our JSON to observables:

For example:

var jsonData = { AllowNotifications: true };

var mapping = {
    'AllowNotifications': {
        create: function(options) { 
            return options.data ? 'true' : 'false';
        }
    }
};

viewModel = ko.mapping.fromJS(jsonData, mapping);

In the example above we are customizing ko.mapping's object creation for the AllowNotifications field.

But if we had several bool properties to convert this would be redundant and cumbersome so here is a slightly more elegant approach:

var jsonData = { AllowNotifications: true };

var boolToString = { create: function (options) { return options.data ? 'true' : 'false'; } };

var mapping = {
    'AllowNotifications': boolToString,
    'AnotherBoolProp': boolToString,
    'YetAnotherBoolProp': boolToString
};

var viewModel = ko.mapping.fromJS(jsonData, mapping);

Details are available in the KO documentation: http://knockoutjs.com/documentation/plugins-mapping.html

Upvotes: 3

Related Questions