Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 585
Arbejdsglæde Avatar asked Jun 15 '12 05:06

Arbejdsglæde


People also ask

How do you find the value of the observable Knockout?

Creating an Observable Variable - var myObservable = ko. observable(); myObservable('Hello'); alert(myObservable()); Assign ko. observable function to a variable. Knockout then converts the variable into a function and tracks when the value changes to notify the UI elements associated with the variable.

Which function is used to perform computation in KnockoutJS?

Computed Observable is a function which is dependent on one or more Observables and automatically updates whenever its underlying Observables (dependencies) change.

What is the use of observable in KnockoutJS?

Knockout. js defines an important role when we want to detect and respond to changes on one object, we uses the observable. An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted.

What is applyBindings in Knockout?

applyBindings do, The first parameter says what view model object you want to use with the declarative bindings it activates. Optionally, you can pass a second parameter to define which part of the document you want to search for data-bind attributes. For example, ko.


1 Answers

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.

like image 58
Mark Robinson Avatar answered Oct 06 '22 03:10

Mark Robinson