我有一个剔除视图模型,其中具有货币和百分比存储为数字(而不是文本)。我想在各个地方以一种很好的文本格式显示这些数字。也就是说,其中一些位于独立的span元素内,如下所示:
<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代码,以满足我的非敲除格式需求和敲除格式,从而消除了在我的代码中使用双重功能来格式化文本文本的需要。
最佳答案
为什么不从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());