【问题标题】:knockout format data without binding handlers没有绑定处理程序的淘汰赛格式数据
【发布时间】:2014-04-24 11:25:19
【问题描述】:

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

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

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

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 和泛型函数。我的问题是,我是否可以以某种方式使用这种通用的 formatCurrency 代码等来满足我的非敲除格式需求和敲除格式的需求,从而消除了在我的代码中使用双重函数来格式化我的文本文本的需要。

【问题讨论】:

    标签: javascript jquery data-binding knockout.js


    【解决方案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());
    

    【讨论】:

      【解决方案2】:

      您可以考虑使用计算的 observables。例如,在您的视图模型中,您可以有一个名为 formattedPrice 的计算 observable(只是一个示例):

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

      actualPrice 将是您在视图模型中的可观察值,其价格为数字。

      更多关于计算的 observables:http://knockoutjs.com/documentation/computedObservables.html

      【讨论】:

      • 这仍然重复了我的工作。我将拥有 observables、计算 observables(进行格式化),并且我仍然拥有进行非基于 KO 的格式化的通用 javascript 方法。
      • IMO,您需要具有基于 KO 和非基于 KO 的格式化功能。我不认为有逃避的余地。不过,我可能是错的。
      猜你喜欢
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 2014-11-29
      • 2016-01-22
      • 2015-03-23
      • 1970-01-01
      相关资源
      最近更新 更多