ko.computed do not fire function upon instantiatin

2019-07-20 21:37发布

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?

2条回答
时光不老,我们不散
2楼-- · 2019-07-20 22:09

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 });
查看更多
啃猪蹄的小仙女
3楼-- · 2019-07-20 22:21

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>  

查看更多
登录 后发表回答