Search code examples
knockout.jsknockout-validation

How to control how empty strings are updated and serialized


Here's a JSFiddle to demostrate my issue: http://jsfiddle.net/jeffreyrswenson/YMFec/7/

I have a viewmodel that has one or more observables. I create most of them like:

var x = ko.observable();

When I tab though the input elements, the values are changed from undefined to "". Because I serialize the VM as part of some "Dirtyflag" logic, the value being changed is causing some problems.

I tried:

var x = ko.observable("");

This causes knockout-validation to not work as I'd like.

I can use this.toJSON() or a JSON replacer to make sure that the JSON is serialized the way I'd like it to be serialized. (I prefere this.toJSON(), but can use either or both)

So is there a better way to do this? Like is there a way to tell Knockout to leave a value as undefined if an input is empty?


Solution

  • Like is there a way to tell Knockout to leave a value as undefined if an input is empty?

    You could use a binding handler to do that. See updated fiddle

    ko.bindingHandlers.undefinedVal = {
        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var value = valueAccessor();
            if (ko.isObservable(value)) {
                if (value.length === 0) {
                    $(element).text(typeof "undefined");
                } else {
                    $(element).text(value);
                }
            }
    
        }
    };