Skip to content

Instantly share code, notes, and snippets.

@codenamejason
Created December 6, 2017 15:31
Show Gist options
  • Save codenamejason/72486bca48b8f1b9d653e7eba0aee244 to your computer and use it in GitHub Desktop.
Save codenamejason/72486bca48b8f1b9d653e7eba0aee244 to your computer and use it in GitHub Desktop.
Custom binding for displaying money values
// binding for displaying money values
ko.bindingHandlers.numericText = {
update: function (element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
var precision = ko.utils.unwrapObservable(allBindingsAccessor().precision) ||
ko.bindingHandlers.numericText.defaultPrecision;
if (value === undefined || value === null) {
return;
}
var formattedValue = Number(value).toFixed(precision);
ko.bindingHandlers.text.update(element, function() {
return "$" + formattedValue;
});
},
// Default of 2 decimal places**
defaultPrecision: 2
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment