没有绑定处理程序的knockout格式数据

时间:2014-04-24 11:25:19

标签: javascript jquery data-binding knockout.js

我有一个淘汰视图模型,其中包含货币和百分比存储为数字(而不是文本)。我想在不同的地方以漂亮的文本格式显示这些数字。即其中一些属于独立的span元素,如下所示:

<span data-bind="formatCurrency: totalOutstandingBalance"></span>

其他人进入表,并使用递归来显示它们。我可以使用绑定处理程序来格式化这些值,特别是对于knockout,就像这样(这个工作):

ko.bindingHandlers.formatCurrency = {
        init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
            ko.applyBindingsToNode(element, {text: valueAccessor, '$#,##0.#0')});
        }
    };

但是,在我的代码(内部图形库)中的某些时候,我需要使用类似的格式代码,就像这样(这适用于内部库):

function formatCurrency(value) {
    return lib.formatter.formatNumber(value, '$#,##0.#0');
}

console.log(formatCurrency(512.17));

我必须格式化各种事物,百分比,货币,整数,双打,日期等。我现在已经为每个实例积累了bindingHandlers和泛型函数。我的问题是我是否可以以某种方式使用这种通用格式的货币代码等,对于我的非淘汰格式化需求和我的淘汰格式化,从而消除了在我的代码中使用格式化文本文本的双重功能的需要。

2 个答案:

答案 0 :(得分:1)

为什么不从bindingHandler调用formatCurrency方法?

function formatCurrency(value) {
    return lib.formatter.formatNumber(value, '$#,##0.#0');
}

ko.bindingHandlers.formatCurrencyHandler = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
        $(element).html(formatCurrency(valueAccessor);
    }
};

如果您确定要获得一个号码,您甚至可以将formatCurrency添加到号码原型中:

Number.prototype.formatCurrency = function () { return lib.formatter.formatNumber(this, '$#,##0.#0'); }

$(element).html(valueAccessor.formatCurrency());

答案 1 :(得分:0)

您可以考虑使用计算的可观察量。例如,在viewmodel中,您可以拥有一个名为formattedPrice的计算可观察对象(仅作为示例):

self.formattedPrice = ko.computed(function () {
      return lib.formatter.formatNumber(self.actualPrice(), '$#,##0.#0');
});

actualPrice将是您的viewmodel中具有数量价格的可观察数据。

有关计算可观察量的更多信息:http://knockoutjs.com/documentation/computedObservables.html