Reputation: 1703
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>
Upvotes: 0
Views: 77
Reputation: 6045
well in the link you provided they are creating a function using fn
which has the computation logic for getting the re-evaluation
count
Better way would be using inbuilt functions isInitial
and getDependenciesCount
of computed under computedContext
.
Logic :
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);
});
As per Docs :
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() — 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
Upvotes: 1