12

我正在使用敲除来填充表格中的数值:

HTML:

<tbody data-bind="foreach: commision">
             <tr>
                 <td>
                    <span>R </span><span data-bind="text: Amount"></span>
                 </td>
             </tr>...
</tbody>

Knockout.js 部分涉及金额和佣金

 var vm = {
            commision: ko.observable(),
            futurecommision: ko.observable(),
            commisionpaid: ko.observable(),
            totals: ko.observable(),
            commisionPaid: ko.observable(ko.utils.unwrapObservable(ko.mapping.fromJS({
                Date: null,
                Amount: 0
            }))),
...

现在我如何显示以十进制格式填充的数字,比如 .00 ?例如。10.00

目前它只显示数字,例如 10

4

2 回答 2

25

您可以考虑编写一个自定义扩展器来处理这个问题。

一个基本的扩展器是这样的:

ko.extenders.numeric = function(target, precision) {
    var result = ko.computed({
        read: function() {
            return target().toFixed(precision); 
        },
        write: target 
    });

    result.raw = target;
    return result;
};

然后将其用于您的可观察对象,例如:

var commissionPaid = ko.observable(whatever your value is).extend({numeric: 2});
于 2013-04-15T07:40:22.680 回答
7

看看这个 KO Money Extender:

http://jsfiddle.net/digitalbush/R6MPU/

(function(){
    var format = function(value) {
        toks = value.toFixed(2).replace('-', '').split('.');
        var display = '$' + $.map(toks[0].split('').reverse(), function(elm, i) {
            return [(i % 3 === 0 && i > 0 ? ',' : ''), elm];
        }).reverse().join('') + '.' + toks[1];

        return value < 0 ? '-' + display : display;
    };

ko.subscribable.fn.money = function() {
    var target = this;

    var writeTarget = function(value) {
        var stripped=value
            .replace(/[^0-9.-]/g, '');

        target(parseFloat(stripped));
    };

    var result = ko.computed({
        read: function() {
            return target();
        },
        write: writeTarget
    });

    result.formatted = ko.computed({
        read: function() {
            return format(target());
        },
        write: writeTarget
    });

    result.isNegative = ko.computed(function(){
        return target()<0;
    });

    return result;
};
})();

//Wire it up
$(function() {
    var viewModel = {
        Cash: ko.observable(-1234.56).money(),
        Check: ko.observable(2000).money(),
        showJSON: function() {
            alert(ko.toJSON(viewModel));
        }
    };


    viewModel.Total = ko.computed(function() {
        return this.Cash() + this.Check();
    }, viewModel).money();
    ko.applyBindings(viewModel);
});
于 2013-04-15T19:58:16.610 回答