Can a Knockout observable be data bound to the value of a radio button?(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/
这篇关于Knockout observable 可以数据绑定到单选按钮的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Knockout observable 可以数据绑定到单选按钮的值吗?
基础教程推荐
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
