Joel Kelly
Joel Kelly

Reputation: 217

KnockoutJS - force number for specific field using ko.mapping plugin

When I use ko.mapping.toJSON it converts any changes I made into strings and they need to be numbers. I tried using the custom mapping like so:

    var mapping = {
   'y': {
        update: function(options) {
                return parseFloat(options.data);
        }
    }
}

... but this only keeps them as numbers inside the contect of the page. Since I am using this to update and external JSON that gets pulled in by HighCharts.js the numbers need to stay numbers even after the toJSON.

From an earlier answer here I was able to use:

//override toJSON to turn it back into a single val
    mappedData.prototype.toJSON = function() {
       return parseInt(ko.utils.unwrapObservable(this.val), 10);  //parseInt if you want or not 
    };

... which worked swimmingly. However this is just a single value type in the JSON so I am unclear on how I could use the same override for it. Do I need to create a whole new object to do this in this instance as well. Or is their something more concise?

Upvotes: 3

Views: 4442

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

Whenever you edit a value in an input, the value will end up being a string. Knockout reads the new value from the element and it is always a string.

If you want to keep it numeric, look at the answer on this question: Knockout.js: time input format and value restriction for a couple of ways to do it. If you use the custom binding (numericValue) in the answer, then you do not need to do anything else with the mapping options. If you use the numericObservable idea, then you would need to use the mapping options to ensure that it was creating these special observable rather than just a normal observable.

Otherwise, you can continue to use the toJSON override as well.

Upvotes: 6

Related Questions