我需要的是拦截从rootsope或任何子范围调用的任何函数。
所以我需要跟踪我的应用程序上的所有类型的东西,并将该数据发送到外部分析服务。
所以在伪代码中我需要的是:
$ rootScope.watch($ rootScope,function(event){
analytics(event.name,event.params);
event.run(); //所以继续发生即将发生的事情...... });
希望这有助于理解我需要的东西。 我似乎无法捕获(拦截)任何功能。
答案 0 :(得分:1)
我认为这是一个有趣的想法所以我继续写了一些东西(fiddle):
// global stats
var stats = {};
// function that will be called and will update stats with timing
function collectStats(f) {
var s = stats[f.toString()];
if (s === undefined) {
s = { name: f.name, count: 0, time: 0 };
stats[f.toString()] = s;
}
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
var start = performance.now();
var result = f.apply(this, args);
var ms = performance.now() - start;
s.count++;
s.time += ms;
return result;
}
// proxy returns a function that can be called like the original
// but that actually calls collectStats() with the function as
// an argument
function proxy(f) {
return collectStats.bind(null, f);
}
您可以这样打电话:
// function to slowly square a number
function squared(a) {
var result = 0;
for (var i = 0; i < a; i++) {
for (var j = 0; j < a; j++) {
result++;
}
}
return result;
}
// proxy for the function that will collect timings
var f = proxy(squared);
// anonymous proxy for an identical function
var f2 = proxy(function(b) {
var result = 0;
for (var i = 0; i < b; i++) {
for (var j = 0; j < b; j++) {
result++;
}
}
return result;
});
var totals = [0, 0, 0];
for (var i = 9000; i < 9005; i++) {
totals[0] += f(i);
totals[1] += f2(i);
// call with inline function
totals[2] += proxy(function(a) { return a * a; })(i);
}