Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Revert an invalid value in knockout without subscriptions firing

Is it possible to revert a value change to a view model with something other than a custom binding handler (maybe an extender) without the subscriptions firing?

For example, say you have a numeric field that only allows values up to 100. If someone types 101, we want the value to drop back to the previous value and most importantly not fire any subscriptions on the reverted value.

I'm trying to find a generic way of accomplishing this without having to write a custom binding handler that inherently would require duplication of core knockout code to handle text fields, select fields, etc.

like image 357
GotDibbs Avatar asked Nov 29 '25 15:11

GotDibbs


1 Answers

Yes, it can be done with an extender, like this:

ko.extenders.numeric = function(target, properties) {
    var result = ko.computed({
        read: target,
        write: function(newValue) {
            var current = target();
            var valueToWrite = newValue;
            if(properties) {
                if(properties.maxNum && properties.maxNum < newValue) {
                    valueToWrite = current;
                }
                if(properties.minNum && properties.minNum > newValue) {
                    valueToWrite = current;
                }
            }

            if(valueToWrite !== current) {
                target(valueToWrite);
            } else {
                target.notifySubscribers(valueToWrite);
            }
        }
    });

    result(target());
    return result;
};

And this is how you use it:

self.number = ko.observable().extend({numeric: { minNum: 50, maxNum: 100} });

You can test that in the fiddle I've created.

You can comment the target.notifySubscribers(valueToWrite) line but what will happen is that if you change that value from outside (like in an input element), the value will not be updated back to the previous one.

like image 191
Jalayn Avatar answered Dec 02 '25 03:12

Jalayn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!