我正在 Angular 中进行性能测试,我想确切地知道我的页面中有多少个 watch 。事实证明,没有简单的方法可以做到这一点。有人尝试过吗?
任何帮助将不胜感激!
最佳答案
我也有同样的问题。我创建了一个可以执行此操作的函数:
// 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/
关于javascript - 一个页面中有多少个 watch ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18704503/