我正在尝试显示并编辑从下拉列表中选择的可观察存储视图作为百分比。不太确定如何在计算函数的读/写中获取和引用 observable。这不起作用...
http://jsfiddle.net/PastorBones/zmdJb/
脚本
function viewModel(){
var self = this;
self.data = [
{name: 'Test1', percent: ko.observable(.1)},
{name: 'Test2', percent: ko.observable(.543)},
{name: 'Test3', percent: ko.observable(.0123)}
];
self.selOption = ko.observable();
self.chosenOptions = ko.observableArray();
self.addData = function(){
if(typeof(self.selOption) !== 'undefined'){
self.chosenOptions.push(self.selOption());
self.selOption(undefined);
}
}
self.formatAsPercent = ko.computed({
read: function(obj){
if(typeof(obj) === 'undefined') return '';
return (obj.percent() * 100).toFixed(2) + '%';
},
write: function(obj){
var val = obj.percent().replace('%','');
obj.percent(val / 100);
}
});
}
ko.applyBindings(new viewModel());
HTML
<select data-bind="options: data, optionsText: 'name', optionsCaption: 'Choose...', value: selOption"></select>
<button data-bind="click: addData, enable: typeof(selOption()) !== 'undefined'">+</button>
<div data-bind="foreach: chosenOptions">
<div>
<span data-bind="text: $data.name"></span>
<input data-bind="value: $root.formatAsPercent($data)" />
</div>
</div>