1

値バインディングを使用して監視可能な境界を持つページに入力があります。ただし、新しい値が指定された文字数未満の場合、オブザーバブルへの書き込みをブロックするエクステンダーがあります。

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;
};

入力ボックスの値をクリアしてもボックスが古い値に戻されない場合を除いて、これはうまく機能します (ただし、オブザーバブルは正しく更新されません)。したがって、基本的には、オブザーバブルが更新されていなくても、入力ボックスを強制的にオブザーバブルから更新する方法が必要です。これは、動作を示す 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 に答える