简体   繁体   中英

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 mydunamicfield property 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM