Skip to content

Instantly share code, notes, and snippets.

@weikinhuang
Created October 20, 2014 19:24
Show Gist options
  • Save weikinhuang/6b7f11b59d4a08e35f83 to your computer and use it in GitHub Desktop.
Save weikinhuang/6b7f11b59d4a08e35f83 to your computer and use it in GitHub Desktop.
Count angular watchers within an element
(function (window) {
var slice = [].slice;
window.ngWatchCount = function(base) {
var elems;
if (base && typeof base !== "string") {
elems = slice.call(base.querySelectorAll("*"));
elems.unshift(base);
} else if (typeof base === "string") {
elems = slice.call(document.querySelectorAll(base + ", " + base + " *"));
} else {
elems = slice.call(document.querySelectorAll("*"));
}
return elems.map(function(elem) {
var data = angular.element(elem).data();
//if (data.$scope && data.$scope.$$watchers && data.$scope.$$watchers.length) {
// elem.setAttribute("angular-watch-count", data.$scope.$$watchers.length);
//}
return data.$scope || null;
}).filter(function(scope) {
return scope && scope.$$watchers;
}).reduce(function(tmp, scope) {
if (tmp.cache[scope.$id]) {
return tmp;
}
tmp.cache[scope.$id] = true;
tmp.count += scope.$$watchers.length;
return tmp;
}, {
count : 0,
cache : {}
}).count;
};
})(window);
// usage
// ngWatchCount(document.getElementById("foo")) => 200 (passing a dom element)
// ngWatchCount(".some-qsa-query") => 900 (passing a querySelectorAll selector string, selector included)
// ngWatchCount() == ngWatchCount(document) => 1400 (no argument, will find all watches)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment