再会
我发现以下两个小提琴完全符合我的要求:
第一个小提琴给了我十进制表示法。
第二个小提琴给了我数字的数字分组。
我的问题:如何将它们组合成一个,以便我可以像这样使用它:
<b data-bind="commaDecimalFormatter: myNumber">This will output both demical notation and digital grouping</b>
==================================================== ==================================================== ==================================================== ===============
小提琴1代码:
// Formatting Functions
function formatWithComma(x, precision, seperator) {
var options = {
precision: precision || 2,
seperator: seperator || '.'
}
var formatted = parseFloat(x,10).toFixed( options.precision );
var regex = new RegExp(
'^(\\d+)[^\\d](\\d{' + options.precision + '})$');
formatted = formatted.replace(
regex, '$1' + options.seperator + '$2');
return formatted;
}
function reverseFormat(x, precision, seperator) {
var options = {
precision: precision || 2,
seperator: seperator || ','
}
var regex = new RegExp(
'^(\\d+)[^\\d](\\d+)$');
var formatted = x.replace(regex, '$1.$2');
return parseFloat( formatted );
}
// END: Formatting Functions
// Custom Binding - place this in a seperate .js file and reference it in your html
ko.bindingHandlers.commaDecimalFormatter = {
init: function(element, valueAccessor) {
var observable = valueAccessor();
var interceptor = ko.computed({
read: function() {
return formatWithComma( observable() );
},
write: function(newValue) {
observable( reverseFormat(newValue) );
}
});
if( element.tagName == 'INPUT' )
ko.applyBindingsToNode( element , {
value: interceptor
} );
else
ko.applyBindingsToNode( element , {
text: interceptor
} );
}
}
// this is your viewmodel
var vm = {
myNumber: ko.observable(100000)
}
// when the DOM is ready, call ko.applyBindings with your viewmodel
$(function() {
ko.applyBindings(vm);
});
小提琴 2 代码:
(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(1000000).money(),
};
viewModel.Total = ko.computed(function() {
return this.Cash();
}, viewModel).money();
ko.applyBindings(viewModel);
});