-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracker.js
117 lines (95 loc) · 3 KB
/
tracker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
(function(window, ko, undefined) {
window.ko_dependencies = function (sendResults, manuallySendResults) {
return function tracker(viewModel) {
var serverId = null,
observables = [],
maxDepth = 1000,
currentDepth = 0,
currentlyTracking = true,
lastUpdate = ko.observable(),
lastUpdateWatcher = ko.computed(lastUpdate).extend({ throttle: 1000 }),
walkTheGraph = function (o, formPropertyName) {
var visited = '__ko__sub_tracker__';
if (currentDepth < maxDepth) {
currentDepth++;
for (var i in o) {
(function closure(o, i) {
if (o.hasOwnProperty(i) && o[i] && (ko.isObservable(o[i])) || ko.isComputed(o[i])) {
var subscriberToken = (function() {
return {
name: formPropertyName(i),
count: 0
};
}()),
latestObservableValue = o[i]();
o[i].subscribe(function () {
if (currentlyTracking) {
subscriberToken.count++;
if(!manuallySendResults) {
lastUpdate.notifySubscribers('');
}
}
});
observables.push(subscriberToken);
o[i][visited] = true;
if (latestObservableValue && !latestObservableValue[visited]) {
walkTheGraph(latestObservableValue, function (childProperty) { return formPropertyName(i) + '().' + childProperty; });
latestObservableValue[visited] = true;
}
}
if (o[i] && !o[i][visited]) {
walkTheGraph(o[i], function (childProperty) { return formPropertyName(i) + '.' + childProperty; });
}
}(o, i));
}
o[visited] = true;
}
currentDepth--;
},
orderBy = function(getProperty) {
return function(a,b) {
if (getProperty(a) > getProperty(b)) return -1;
if (getProperty(a) < getProperty(b)) return 1;
return 0;
};
},
orderByCount = orderBy(function(a) { return a.count; }),
orderByName = orderBy(function(a) { return a.name; }),
getCount = function (order) {
return observables.sort(order || orderByCount);
},
postResultsUntilSuccessful = function() {
var results = getCount(),
tryUntilSuccessful = function() {
sendResults(
{
results: results,
id: serverId
},
function success(response) {
serverId = response.id;
},
tryUntilSuccessful);
};
tryUntilSuccessful();
};
walkTheGraph(viewModel, function identity(childProperty) { return childProperty; });
postResultsUntilSuccessful();
lastUpdateWatcher.subscribe(postResultsUntilSuccessful);
return {
getCount: getCount,
start: function () {
currentlyTracking = true;
},
stop: function () {
currentlyTracking = false;
},
sendResults: function() {
postResultsUntilSuccessful();
},
orderByCount: orderByCount,
orderByName: orderByName
};
};
}
}(window || {}, ko));