1

我的页面上有一个使用值绑定具有可观察绑定的输入。但是,我有一个扩展器,如果新值小于指定的字符数,它会阻止对 observable 的写入:

ko.extenders.minLengthRevert = function(target, minLength) {
    "use strict";

    //create a write able computed observable to intercept writes to our observable
    var result = ko.computed({
        read: target,  //always return the original observables value
        write: function(newValue) {
            var current = target();
            if (current !== newValue){
                if (newValue.length >= minLength){
                    target(newValue);
                }
            }
        }
    });

    //return the new computed observable
    result(target());
    return result;
};

这很好用,除非我清除输入框的值,否则该框不会恢复为旧值(但 observable 不会正确更新)。所以基本上我需要一些方法来强制输入框从 observable 更新,即使 observable 没有更新。这是一个演示行为的 JSFiddle:http: //jsfiddle.net/4Z5bp/

4

1 回答 1

3

添加“else { target.notifySubscribers(current); }”子句。这将诱使文本框认为值已更改,并将自行重置:

ko.extenders.minLengthRevert = function(target, minLength) {
    "use strict";

    //create a write able computed observable to intercept writes to our observable
    var result = ko.computed({
        read: target,  //always return the original observables value
        write: function(newValue) {
            var current = target();
            if (current !== newValue){
                if (newValue.length >= minLength){
                    target(newValue);
                }
                else {
                    // forces textbox which is performing the write() to think
                    // the value has changed and reset itself.
                    target.notifySubscribers(current);
                }
            }
        }
    });

    //return the new computed observable
    return result;
};

你也不需要result(target());,因为它什么都不做。

于 2013-08-01T20:36:03.863 回答