How to force the default string to be null instead of ""

In knockoutjs, you can bind a string to an input tag. If you don't interfere with that input, the line remains null

, but if you type something and then clear it, it will jump to an empty line. How can I override this behavior globally without changing every binding.

Greetings.

Sam

+3


source to share


2 answers


You can create a "new" observable function that wraps the computed responsibility for converting empty strings to zero. Then use it whenever you want to set null values:

JS:

var forceNullObservable = function() {
    var obs = ko.observable();

    return ko.computed({
        read: function() {
            return obs();
        },
        write: function(val) {
            if(val === '') {
                val = null;
            }
            obs(val);
        }
    });
};

// use forceNullObservable instead of ko.observable
vm = {
    val: forceNullObservable()
}

ko.applyBindings(vm);

      

Html:

<input type="text" data-bind="value: val"/>

      

#

Demo: JSFiddle


Edit:




Modification forceNullObservable

to accept an external observable will allow you to achieve what you want without changing the js code:

JS:

window.forceNullObservable = function(obs) {

    return ko.computed({
        read: function() {
            return obs();
        },
        write: function(val) {
            if(val === '') {
                val = null;
            }
            obs(val);
        }
    });
};

vm = {
    val: ko.observable()
}

ko.applyBindings(vm);

      

Html:

<input type="text" data-bind="value: forceNullObservable(val)"/>

      

#

Demo: JSFiddle

+3


source


I don't think you can do this globally, but you can use a custom value binding like:

Js

ko.bindingHandlers.nonBlankValue = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        // Subscribe to changes to the observable bound to the value binding:
        allBindingsAccessor().value.subscribe(function(newValue) {
            if (newValue === "") { this.target(null); }
        });
        // Initialise the standard underlying KO value binding:
        ko.bindingHandlers.value
            .init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
    }
    update: ko.bindingHandlers.value.update
};

      



Markup

<input type="text" data-bind="nonBlankValue: modelProperty" />

      

0


source







All Articles