Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String empty to null custom binding

Based on this answer Knockout.js: time input format and value restriction, i'm trying to create a custom binding that sets observable to null if the value is string empty, here is the code that's not working, Ip observable is always null on model

ko.bindingHandlers.stringEmptyNull = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var underlyingObservable = valueAccessor();
            var interceptor = ko.dependentObservable({
                read: underlyingObservable,
                write: function (value) {
                    if (value != null && value.trim() == '')
                        underlyingObservable();
                }
            });
            ko.bindingHandlers.value.init(element, function () { return interceptor }, allBindingsAccessor);
        },
        update: ko.bindingHandlers.value.update
    };

input:

<input type="text" data-bind="stringEmptyNull: Ip" />

Model:

var Model = function () {
        this.Ip = ko.observable()
        ko.applyBindings(this, $myForm[0]);
    };

    instance = new Model();
like image 755
Alexandre Avatar asked Sep 28 '13 15:09

Alexandre


People also ask

Is empty string considered null?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .

Why use null instead of empty string?

An empty string is useful when the data comes from multiple resources. NULL is used when some fields are optional, and the data is unknown.

Is null or empty Java string?

In Java, there is a distinct difference between null , empty, and blank Strings. An empty string is a String object with an assigned value, but its length is equal to zero. A null string has no value at all.


1 Answers

Your problem is in your interceptor.

In your write function you need to set the underlyingObservable to null when the value is an empty string (calling only underlyingObservable(); only gets its value but does not set its value to null) and you also need to pass value to underlyingObservable in every other case:

var interceptor = ko.dependentObservable({
    read: underlyingObservable,
    write: function (value) {
        if (value != null && value.trim() == '')
            underlyingObservable(null);
        else
            underlyingObservable(value);
    }
});

Demo JSFiddle. (Open your browser's console then type something in the textbox and then clear the textbox)

like image 93
nemesv Avatar answered Nov 15 '22 07:11

nemesv