I am using knockout to populate number values inside a table:
HTML:
-
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)
-
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)
- 热议问题