我有一个不起作用的代码。 这是http://jsfiddle.net/JPBarbosa/uxwTM/4/。
数据绑定参数 optionsValue 不像参数 optionsText 那样有用。
我对两者使用相同的功能!
<select data-bind="options: times, optionsText: function(item) { return item.toLocaleTimeString(); }, optionsValue: function(item) { return item.toLocaleTimeString(); }, value: selectedTime"></select>
问候,JP。
答案 0 :(得分:4)
为optionsValue
传入的对象必须是与要用作值的属性名称对应的字符串。你不能将它设置为这样的值,不幸的是它与optionsText
的工作方式不同。
将times
数组映射到您想要的值会更容易。
<select data-bind="options: ko.utils.arrayMap(times(), function (time) { return time.toLocaleTimeString(); }), value: selectedTime"></select>
虽然您希望将映射代码保留在视图之外。因此,向视图模型添加一个计算的observable,它返回映射的值。
var ViewModel = function() {
// ...
self.mappedTimes = ko.computed(function () {
return ko.utils.arrayMap(self.times(), function (time) {
return time.toLocaleTimeString();
});
})
};
<select data-bind="options: mappedTimes, value: selectedTime"></select>