Last active
April 3, 2018 13:32
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }); | |
} | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<input data-bind="valueNumber: myNumber, numberFormat: 'n0'" class="number" /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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') {