Skip to content

Instantly share code, notes, and snippets.

@johnnyreilly
Last active April 3, 2018 13:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnnyreilly/5620704 to your computer and use it in GitHub Desktop.
Save johnnyreilly/5620704 to your computer and use it in GitHub Desktop.
A value number style binding for Knockout made using Globalize for parsing / formatting
ko.bindingHandlers.valueNumber = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// This will be called when the binding is first applied to an element
// Set up any initial state, event handlers, etc. here
var observable = valueAccessor(),
properties = allBindingsAccessor();
var interceptor = ko.computed({
read: function () {
var format = properties.numberFormat || "n2";
return Globalize.format(observable(), format);
},
write: function (newValue) {
var number = Globalize.parseFloat(newValue);
if (number) {
observable(number);
}
}
});
if (ko.utils.tagNameLower(element) === 'input') {
ko.applyBindingsToNode(element, { value: interceptor });
} else {
ko.applyBindingsToNode(element, { text: interceptor });
}
}
};
<input data-bind="valueNumber: myNumber, numberFormat: 'n0'" class="number" />
@b1ade68
Copy link

b1ade68 commented Dec 20, 2017

John, ko.utils.tagNameLower is not available in minified version of knockout, so this script doesn't work in production.
I suggest to change the line
if (ko.utils.tagNameLower(element) === 'input') {
with:
if (element && element.tagName && element.tagName.toLowerCase()=== 'input') {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment