Question

I'm trying use knockout.js' computed observables to setup C#-like properties on a model. I want observable to only accept valid values. Simplified example:

function Model()
{
    var a = 100;
    var b = 200;

    var $ = this;
    this.a = ko.computed({
        read: function(){return a},
        write: function(value){
            var newval = parseFloat(value, 10);
            if(newval < 1000) 
                a = newval;
        }});

    this.b = ko.observable(b);
}

Writing to a hover does not update the bindings. Is it possible to enable changing a as if it were a regular member of the Model but with extra functionality attached?

I know I can use second observable to contain the actual value and rely on it's update mechanism, but this approach becomes cumbersome quickly with increasing number of computed properties of this kind.

Was it helpful?

Solution

Computed observable is not suitable for your example, since a computed observable is a function that should depend on one or more other observables.

You can instead use extenders to achieve this. Here's a fiddle with a demo.

ko.extenders.maxNumber = function(target, option) {
    var result = ko.computed({
        read: target,
        write: function(value){
            var newval = parseFloat(value, 10);
            if (newval < option) {
                target(newval);
            } else {
                alert('Number is to big');
            }
        }
    });

    result(target());

    return result;
};

function Model() {
    var a = 100;
    this.a = ko.observable(a).extend({ maxNumber: 1000 });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top