Arbejdsglæde
Arbejdsglæde

Reputation: 14098

Knockout.js - how do I get the value of an observable property inside a computed observable?

I have following Knockout.js object:

var viewModel = {
    description : ko.observable(""),
    Name : ko.observable(""),
    productid : ko.observable(""),
    productmodel : ko.observable(""),
    productnumber : ko.observable(""),
    text_relevance : ko.observable(""),
    mydunamicfield : ko.computed(function() {
        return "bq=(and " +
            ((this.description == "") ? "" : ("description:" + this.description + " ")) +
            ")";
    } , this)
};

But the mydunamicfieldproperty isn't producing the the correct concatenated result. If I try to reference this.description() inside another function, I see the following error message when the page is loading:

Property 'description' of object [object Window] is not a function

What is the problem in this case?

Upvotes: 15

Views: 29396

Answers (1)

Mark Robinson
Mark Robinson

Reputation: 13278

Firstly, you must reference this.description as this.description() if you want to get its value.

Secondly, try putting your computed field outside your viewModel (as 'this' which is the viewModel itself isn't defined at the point you create the computed observable.

See http://jsfiddle.net/rAEqK/2/ for a working example.

Upvotes: 20

Related Questions