可以观察到一个Knockout可以将数据绑定到单选按钮的值吗? [英] Can a Knockout observable be data bound to the value of a radio button?

查看:617
本文介绍了可以观察到一个Knockout可以将数据绑定到单选按钮的值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用值绑定将Knockout observable属性绑定到单选按钮吗?

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

这是我要做的,但是值得结束作为字符串[Object object],而不是我的observable属性的实际实例:

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可观察中。

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

推荐答案

如下所述这里
只有选择节点有能力将任意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/

这篇关于可以观察到一个Knockout可以将数据绑定到单选按钮的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆