跟踪淘汰赛中的评估数 [英] track number of evaluations in knockout
问题描述
我想知道如何跟踪下面的GetArray1()和GetArray2()的可剔除可观察数组中的评估数. 我已经阅读了 fiddle链接中的示例,但不确定如何安装它进入这种情况.
I would like to know how to I track the number of evaluation in knockout observable array for GetArray1() and GetArray2() below. I have read a sample from this fiddle link but not sure how to fit it into this situation.
var data1 = [{
"Hours": 1
}, {
"Hours": 2
}, {
"Hours": 3
}];
function ViewModel() {
var self = this;
self.sampleArray = ko.observableArray([]);
var newData = ko.mapping.fromJS(data1)();
self.GetArray = function() {
ko.utils.arrayForEach(newData, function (item) {
self.sampleArray.push(item) //push here
});
}
self.GetArray2 = function() {
$.each(newData, function (index, value) {
self.sampleArray.push(value) //push here
});
}
self.GetArray();
self.GetArray2();
}
ko.applyBindings(new ViewModel())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<div data-bind="foreach:sampleArray">
<p data-bind="text:Hours"></p>
<br/>
</div>
推荐答案
在您提供的链接中,他们正在使用fn
创建函数,该函数具有用于获取re-evaluation
计数的计算逻辑
well in the link you provided they are creating a function using fn
which has the computation logic for getting the re-evaluation
count
更好的方法是使用在computedContext
下计算的内置函数isInitial
和getDependenciesCount
.
Better way would be using inbuilt functions isInitial
and getDependenciesCount
of computed under computedContext
.
逻辑:
ko.computed(function () {
var subscribe = self.sampleArray(); //declared on top to subscribe initially
if (ko.computedContext.isInitial()) return true;
var count = ko.computedContext.getDependenciesCount();
self.revaluationCount(self.revaluationCount() + count);
});
根据文档:
isInitial()—如果在第一次调用时调用此函数,则返回true 曾经评估过当前计算得出的可观察值,或者为false 否则.对于纯计算的可观察物,isInitial()始终为 未定义.
isInitial() — A function that returns true if called during the first ever evaluation of the current computed observable, or false otherwise. For pure computed observables, isInitial() is always undefined.
getDependenciesCount()-返回依赖项的数量 在当前评估过程中,到目前为止已检测到的计算出的可观测值.
getDependenciesCount() — Returns the number of dependencies of the computed observable detected so far during the current evaluation.
在此处查看完整的 文档 .
Check here for complete documentation .
具有完整代码的工作示例 此处
working sample with complete code here
这篇关于跟踪淘汰赛中的评估数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!