字符串为空以自定义绑定

时间:2013-09-28 15:26:38

标签: knockout.js custom-binding

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

上始终为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();

1 个答案:

答案 0 :(得分:8)

您的问题出在interceptor

write功能中,当underlyingObservable为空字符串时,您需要将null设置为value(仅调用underlyingObservable();只会获取其值但是没有将其值设置为null) 在其他所有情况下,您还需要将value传递给underlyingObservable

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

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