Knockout observable 可以数据绑定到单选按钮的值吗?

是否可以使用值绑定将 Knockout 可观察属性绑定到单选按钮?

Is it possible to bind a Knockout observable property to a radio button using a value binding?

这是我想要做的,但值最终是字符串[Object object]",而不是我的可观察属性的实际实例:

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();
}

所以最后我希望 Car 或 Truck VehicleViewModel 在 selectedVehicleGroup observable 中.

So in the end I would like either the Car or Truck VehicleViewModel to be in the selectedVehicleGroup observable.

推荐答案

如文档所述这里只有 Select 节点能够将任意 JavaScript 对象绑定到一个值.其他输入需要一个字符串值,这就是您的值返回[Object object]"的原因.

As documented here only Select nodes have the ability to bind an arbitrary JavaScript object to a value. Other inputs require a string value, which is why your value is returning "[Object object]".

你仍然可以做你想做的事,但你必须手动映射一个键并自己找到合适的对象.这是一个演示的小提琴:

You can still do what you want but you will have to manually map a key and find the appropriate object yourself. Here is a fiddle that demonstrates:

http://jsfiddle.net/jearles/JcPXy/

相关文章