【问题标题】:How many watches are there in a page?一页有多少只手表?
【发布时间】:2013-09-29 03:59:10
【问题描述】:

我正在使用 Angular 进行性能测试,我想知道我的页面中有多少只手表。事实证明,没有简单的方法可以做到这一点。有人试过吗?

任何帮助将不胜感激!

【问题讨论】:

  • 快速而肮脏的解决方案的想法:注册全局计数器,并在负责注册/注销手表的方法中增加/减少它。当然——你必须编辑 Angular.js 代码。
  • 你可以在本地包装angular的.$watch,使用本地版本,可以记录或推送到你需要的任何地方。
  • 检查$scope.watchers
  • 是的,在本地包装比直接编辑 angular 的代码更好(正如@dandavis 建议的那样)
  • @dandavis 你能给我举个例子吗?

标签: javascript performance angularjs watch


【解决方案1】:

我也有同样的问题。我创建了一个可以做到这一点的函数:

// 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/

【讨论】:

  • 这是否包括 isoloatedScopes?如果不是如何包含它们?
猜你喜欢
  • 1970-01-01
  • 2011-08-08
  • 1970-01-01
  • 1970-01-01
  • 2012-08-26
  • 1970-01-01
  • 2021-03-12
  • 2016-10-13
  • 2016-08-25
相关资源
最近更新 更多