1
votes

I have an input on my page that has a observable bound using the value binding. However, I have an extender which blocks the write to the observable if the new value is less than a specified number of characters:

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

This works well except if I clear the value of the input box the box doesn't get reverted to the old value (but the observable correctly does not get updated). So basically I need some way to force the input box to update from the observable even though the observable didn't get updated. Here's a JSFiddle demonstrating the behavior: http://jsfiddle.net/4Z5bp/

1

1 Answers

3
votes

Add an "else { target.notifySubscribers(current); }" clause. This will trick the textbox into thinking the value has changed and it will reset itself:

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

Also you don't need result(target()); since it does nothing.