RullDawg
RullDawg

Reputation: 221

How do I constrain an observable to only be a certain set of values in Knockout.js?

I have the following input type bound to a "page" observable in my view model.

<input type="text" data-bind="value: page"/>

The user can enter any value in the text input, but I'd only want the binding to occur in my model if the value is within a list of values. I looked into the knockout-validation framework and have built the proper extends to raise that an error has occurred, but I cannot find a way to ensure that the "page" property is not updated in my model.

Has anyone else run into this situation with Knockout.js?

Thanks! -Bob

Upvotes: 0

Views: 144

Answers (1)

Brian S
Brian S

Reputation: 1061

You should be able to do this by extending your observable.

The documentation is at http://knockoutjs.com/documentation/extenders.html

Here as an example of what may meet your needs:

ko.extenders.allowedValues = function (target, valuesArray) {
    var result = ko.computed({
        read: target,
        write: function (newValue) {
            if (valuesArray.indexOf(newValue) !== -1) {
                target(newValue);
            } else {
                //handle the user inputting a value not allowed here
            }
        }
    });

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

And then you would create the observable like so:

var page = ko.observable().extend({ 
    allowedValues: [ /* place the allowed values in this array */] });

Upvotes: 2

Related Questions