I have a Knockout binding handler called valueNumber
which parses and displays numbers with a little help from Globalize:
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",
formattedNumber = Globalize.format(ko.utils.unwrapObservable(observable), format);
return formattedNumber;
},
write: function (newValue) {
var currentValue = ko.utils.unwrapObservable(observable),
numberValue = Globalize.parseFloat(newValue);
if (!isNaN(numberValue)) {
if (numberValue !== currentValue) {
// The value has changed so update the observable
observable(numberValue);
}
} else if (newValue.length === 0) {
if (properties.isNullable) {
// If newValue is a blank string and the isNullable property has been set then nullify the observable
observable(null);
} else {
// If newValue is a blank string and the isNullable property has not been set then set the observable to 0
observable(0);
}
}
}
});
if (element.tagName.toLowerCase() === 'input') {
ko.applyBindingsToNode(element, { value: interceptor });
} else {
ko.applyBindingsToNode(element, { text: interceptor });
}
}
};
To use it is pretty straightforward:
<input data-bind="valueNumber: Cost, numberFormat: 'n1', isNullable: true" type="text" value="" />
When an input textbox loses focus the value is displayed based on the numberFormat property. So if a user had entered "1.123" in the textbox above then when they tabbed out "1.1" would be left displayed in the input but the value stored in the observable would be 1.123.
This is where it gets tricky.
When an input element gains focus / becomes the active element I want to display the full value (the 1.123) to the users in the input element. I've got some idea that by depending on hasFocus I could achieve this but I'm not too certain what a "correct" approach would look like.
I'm ideally hoping to wrap this all up within the one binding handler rather than introducing the need for extra markup.
UPDATE
Based on Robert Westerlund's answer I've come up with a JSFiddle that demonstrates the solution nicely. This is essentially Robert's solution but slightly restyled based on the conventions used in the built-in hasFocus
binding.
Oh and just for completeness this solution is using Globalize 0.1.1. Having had a quick look at the GitHub repo it looks like the API for Globalize is going to change at some point in the future.