In my view model I have a IsMale value that has the value true or false.
In my UI I wish to bind it to the following radio buttons:
You can also use an extender so it's easy to reuse them for more observables:
ko.extenders.boolForEditing = function (target, allowNull) {
var result = ko.computed({
read: function () {
var current = target();
var newValue = null;
if (current === undefined || current === null || current === '') {
if (!allowNull) {
newValue = 'false';
}
} else {
newValue = current ? 'true' : 'false';
}
return newValue;
},
write: function (newValue) {
var current = target();
var valueToWrite = null;
if (newValue === undefined || newValue === null || newValue === '') {
if (!allowNull) {
valueToWrite = false;
}
} else {
valueToWrite = newValue === 'true';
}
// only write if it changed
if (valueToWrite !== current) {
target(valueToWrite);
} else {
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
}).extend({
notify: 'always'
});
result(target());
return result;
};
Then use it like this:
this.IsMale.forEditing = this.IsMale.extend({boolForEditing: true});
The parameter provided to boolForEditing indicates whether the value may be null.
See http://jsfiddle.net/G8qs9/1/