1

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.

2
  • 1
    Can you add a jsFiddle example? Also asking users directly for help is generally shunned upon, just FYI.
    – PW Kad
    Commented Mar 10, 2014 at 19:28
  • I'll put up a cut down jsfiddle tomorrow. I'm not asking for a direct solution but i'm not clear what good practice would be for this use case. Commented Mar 10, 2014 at 21:58

1 Answer 1

0

It's always hard to say what a "correct" approach would be, but I'll give you a sample of one approach at least. First, add an observable to keep track of the focus state.

var elementHasFocus = ko.observable(element === document.activeElement);

Next, you need to make sure to change that value when the onblur or onfocus events occur.

element.onblur = function(){ elementHasFocus(false); };
element.onfocus = function(){ elementHasFocus(true); };

The above three lines could be added in the init method, right before you create the interceptor computed observable.

Finally, update the read-method of the interceptor to make sure it determines value based on the focus state.

read: function () {
    if (elementHasFocus()) {
        return ko.unwrap(observable); // If you use newer versions of knockout, you have a convenient ko.unwrap path to the ko.utils.unwrapObservable method.
    }
    else {
        var format = properties.numberFormat || "n2",
            formattedNumber = Globalize.format(ko.utils.unwrapObservable(observable), format);

        return formattedNumber;
    }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.