Hi is there a way to not fire the function when instantiating a ko.computed
example is
i have this ko.computed
ko.computed(function(){ alert(this.Test); } , this);
so basically if i instantiated this computed this will fire the function defined there
is there a way not to fire it upon instantiation? and only fire it when dependency change?
You need to set the deferEvaluation
option:
deferEvaluation
— Optional. If this option is 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. By default, a computed observable has its value determined immediately during creation.
ko.computed(function(){ alert(this.Test); } , this, { deferEvaluation: true });
You can also use a knockout pureComputed
for this. A pure computed only evaluates when there's a dependency.
Example:
var person, fullName,
getFullName = function() {
return person().firstName() + " " + person().lastName();
};
person = ko.observable(null);
// This won't work, because the computed evaluates and getFullName doesn't
// check for `null`
try {
fullName = ko.computed(getFullName);
} catch (err) {
console.log("Regular computed:");
console.log(err.message);
}
// This will work because there's no dependency to `fullName` yet
// At `applyBindings`, `fullName` needs to be evaluated
fullName = ko.pureComputed(getFullName);
person({
firstName: ko.observable("Jane"),
lastName: ko.observable("Doe")
});
ko.applyBindings({ heading: fullName })
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<h3 data-bind="text: heading"></h3>