5

基于这个答案Knockout.js: time input format and value constraint,我正在尝试创建一个自定义绑定,如果值为空字符串,则将 observable 设置为 null,这是不起作用的代码,Ip observable 始终为 null模型

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 type="text" data-bind="stringEmptyNull: Ip" />

模型:

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

    instance = new Model();
4

1 回答 1

8

你的问题在你的interceptor.

在您的函数中,您write需要在为underlyingObservable空字符串null时将valueunderlyingObservable();nullvalueunderlyingObservable

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

演示JSFiddle。(打开浏览器的控制台,然后在文本框中输入一些内容,然后清除文本框)

于 2013-09-28T16:36:05.057 回答