Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Bug in extenders documentation #461

Closed
mikegleasonjr opened this Issue · 2 comments

2 participants

@mikegleasonjr

In the page:
http://knockoutjs.com/documentation/extenders.html

In the section "Live Example 1: Forcing input to be numeric"

If we leave an input blank or with only whitespaces, NaN is appearing in the input.

2 fixes in the extender are required:

  • in the "newValueAsNum" declaration and
  • in the condition near: "target.notifySubscribers(valueToWrite);"

Here's the full code fixed:

ko.extenders.numeric = function(target, precision) {
   //create a writeable computed observable to intercept writes to our observable
   var result = ko.computed({
      read: target,  //always return the original observables value
      write: function(newValue) {
         var current = target(),
            roundingMultiplier = Math.pow(10, precision),
            newValueAsNum = !/\S/.test(newValue) || isNaN(newValue) ? 0 : parseFloat(newValue),
            valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;

         //only write if it changed
         if (valueToWrite !== current) {
            target(valueToWrite);
         } else {
            //if the rounded value is the same, but a different value was written, force a notification for the current field
            if (newValue !== current) {
               target.notifySubscribers(valueToWrite);
            }
         }
      }
   });

   //initialize with current value to make sure it is rounded appropriately
   result(target());

   //return the new computed observable
   return result;
};

Thanks

@rniemeyer
Owner

Thanks for reporting this one. I just committed a fix for it. I did parseFloat(+newValue) to handle blank/whitespace and fixed the equality check on the last part as you had suggested.

@rniemeyer rniemeyer closed this
@mikegleasonjr

Nice trick, the parseFloat(+newValue)

Thank you for this awesome library...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.