使用ko.computed将输入值格式化为百分比

时间:2012-09-28 14:17:12

标签: knockout.js

我正在尝试显示并使可编辑的存储视图可观察从下拉列表中选择为百分比。不太确定如何在计算函数的读/写内获取和引用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>
​

1 个答案:

答案 0 :(得分:3)

要访问子项的属性,应在 child 级别定义计算属性。 请参阅修改过的小提琴:http://jsfiddle.net/zmdJb/3/