观察到淘汰赛可以绑定到一个单选按钮的值数据?(Can a Knockout observable b

2019-06-25 08:16发布

是否有可能淘汰赛观察的属性使用值绑定一个单选按钮绑定?

这里就是我想要做的,但价值最终被字符串“[Object对象]”,而不是我的观察特性的实际例子:

<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" />

下面是我使用的视图模型:

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

所以,最后,我想无论是汽车或卡车VehicleViewModel是在selectedVehicleGroup观察到。

Answer 1:

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/



Answer 2:

FYI其他读者来接受的答案,KO V3添加的CheckedValue结合使得现在这一切成为可能。



Answer 3:

我需要这一点。 我的解决办法类似于约翰Earles除了我使用的computed ,而不是subscribe

self.selectedVehicleGroup = ko.computed(function(){
    return ko.utils.arrayFirst(self.availableGroups(), function (group) { return group.name() == self.selectedGroupOption(); });
});

http://jsfiddle.net/JcPXy/91/



文章来源: Can a Knockout observable be data bound to the value of a radio button?