Knockout强制更新输入值

时间:2013-08-01 20:30:48

标签: knockout.js

我的页面上有一个输入,它使用值绑定具有可观察的绑定。但是,如果新值小于指定的字符数,我有一个扩展器阻止写入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/

1 个答案:

答案 0 :(得分: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());,因为它什么都不做。