I am trying to display and make editable a stored view observable chosen from a dropdown as a percentage. Not quite sure how to obtain and reference the observable inside the read/write of the computed function. This does not work…
http://jsfiddle.net/PastorBones/zmdJb/
Script
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>
To have access to properties of the child, the computed property should be defined at child level.
See the modified fiddle: http://jsfiddle.net/zmdJb/3/