문제

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();
도움이 되었습니까?

해결책

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)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top