Can observed knockouts be tied to a switch value?
Is it possible to bind a knockout observable property to a radio button using value binding?
Here's what I'm trying to do, but the value ends up being the string "Object Object" instead of the actual instance of my observable property:
<input type="radio" name="vehicleGroup" data-bind="checked: vehicleGroupViewModel().selectedGroupOption , value:vehicleGroupViewModel().car" />
<input type="radio" name="vehicleGroup" data-bind="checked: vehicleGroupViewModel().selectedGroupOption , value:vehicleGroupViewModel().truck" />
Here's the view models I'm using:
var VehicleGroupViewModel = function(){
var self = this;
this.selectedVehicleGroup = ko.observable();
this.selectedGroupOption = ko.observable();
this.selectedGroupOption.subscribe(function (newVal) {
self.selectedVehicleGroup(newVal);
}
this.selectedGroup = ko.observable();
this.car = ko.observable(new VehicleViewModel());
this.truck = ko.observable(new VehicleViewModel());
}
var VehicleViewModel = function(){
this.name = ko.observable();
}
So in the end, I would like the vehicle or Truck VehicleViewModel to be in the selected observable vehicle group.
As described here only Nodes have the ability to bind an arbitrary JavaScript object to a value. Other inputs require a string value, so your value returns "[Object Object]".
You can still do what you want, but you have to manually match the key and find the appropriate object yourself. Here is a fiddle that demonstrates:
http://jsfiddle.net/jearles/JcPXy/
FYI for other readers who have come to the accepted answer, KO v3 added the checkedValue binding which now makes this possible.
subscribe
used instead
computed
:
self.selectedVehicleGroup = ko.computed(function(){
return ko.utils.arrayFirst(self.availableGroups(), function (group) { return group.name() == self.selectedGroupOption(); });
});
http://jsfiddle.net/JcPXy/91/