Question

I've just noticed that after I've concatenated my js, all knockout computed observables are being evaluated and called on all pages even if I don't bind the view model that contains them, is this the expected behaviour? If so how can I avoid it?

Was it helpful?

Solution

This is the excepted behavior:

By default, a computed observable has its value determined immediately during creation.

If you want to change this, you need to set the deferEvaluation to true:

then the value of the computed observable will not be evaluated until something actually attempts to access its value or manually subscribes to it.

So your computeds should look like this:

function AppViewModel() {
    this.firstName = ko.observable('Bob');
    this.lastName = ko.observable('Smith');

    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();
    }, this, { deferEvaluation: true });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top