ko.computed do not fire function upon instantiating

a 夏天 提交于 2019-12-24 03:22:47

问题


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?


回答1:


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 });



回答2:


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>  


来源:https://stackoverflow.com/questions/43113909/ko-computed-do-not-fire-function-upon-instantiating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!