Adding decimal formatting to Knockout number data bindings

前端 未结 2 1215
夕颜
夕颜 2021-01-02 01:49

I am using knockout to populate number values inside a table:

HTML:


             
                   


        
相关标签:
2条回答
  • 2021-01-02 02:18

    Have a look at this 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);
    });
    
    0 讨论(0)
  • 2021-01-02 02:24

    You could look into writing a custom extender to handle this.

    A basic extender is something like:

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

    This is then used on your observables like:

    var commissionPaid = ko.observable(whatever your value is).extend({numeric: 2});
    
    0 讨论(0)
提交回复
热议问题