【问题标题】:Knockout force update of input value输入值的敲除力更新
【发布时间】:2013-08-02 23:01:57
【问题描述】:

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

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/

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    添加“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-01-10
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 2015-06-16
      • 2012-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多