我正在Angular进行性能测试,我想知道我的页面中有多少手表。事实证明,没有简单的方法可以做到这一点。还有人试过吗?
任何帮助都将受到高度赞赏!
答案 0 :(得分:2)
我有同样的问题。我创建了一个可以执行此操作的函数:
// get the watch count
// scopeHash is an optional parameter, but if you provide one, this function will modify it for later use (possibly debugging)
function getWatchCount (scope, scopeHash) {
// default for scopeHash
if (scopeHash === undefined) {
scopeHash = {};
}
// make sure scope is defined and we haven't already processed this scope
if (!scope || scopeHash[scope.$id] !== undefined) {
return 0;
}
var watchCount = 0;
if (scope.$$watchers) {
watchCount = scope.$$watchers.length;
}
scopeHash[scope.$id] = watchCount;
// get the counts of children and sibling scopes
// we only need childHead and nextSibling (not childTail or prevSibling)
watchCount+= getWatchCount(scope.$$childHead, scopeHash);
watchCount+= getWatchCount(scope.$$nextSibling, scopeHash);
return watchCount;
}
它将计算任何范围内的观察者数量。计算根作用域可能最有用,但您可以在任何作用域级别使用它(可能用于检查组件上的监视)。以下是一个实例:http://jsfiddle.net/S7APg/