|
| 1 | +/* |
| 2 | + Adds a watch expression on the root scope that counts the number of times |
| 3 | + it was called. After method stops, restores the original method and |
| 4 | + prints number of times digest cycle was run. |
| 5 | + Method can return a promise. |
| 6 | + Typical use: see how many times the full digest cycle is triggered. |
| 7 | +
|
| 8 | + $scope.myMethod = function () ... |
| 9 | + where $scope could be determined from element 'my-selector' |
| 10 | +*/ |
| 11 | +(function countDigestCycles() { |
| 12 | + var selector = 'button'; |
| 13 | + var methodName = 'doSomething'; |
| 14 | + var name = selector + ':' + methodName; |
| 15 | + |
| 16 | + /* global angular */ |
| 17 | + var el = angular.element(document.getElementById(selector)); |
| 18 | + var scope = el.scope() || el.isolateScope(); |
| 19 | + console.assert(scope, 'cannot find scope from ' + name); |
| 20 | + |
| 21 | + var fn = scope[methodName]; |
| 22 | + console.assert(typeof fn === 'function', 'missing ' + methodName); |
| 23 | + var $rootScope = el.injector().get('$rootScope'); |
| 24 | + |
| 25 | + var count = 0; |
| 26 | + $rootScope.$watch(function () { |
| 27 | + count += 1; |
| 28 | + }); |
| 29 | + |
| 30 | + var $q = el.injector().get('$q'); |
| 31 | + |
| 32 | + scope[methodName] = function () { |
| 33 | + |
| 34 | + count = 0; |
| 35 | + |
| 36 | + // method can return a value or a promise |
| 37 | + var returned = fn(); |
| 38 | + $q.when(returned).finally(function finishedMethod() { |
| 39 | + scope.$$postDigest(function () { |
| 40 | + scope[methodName] = fn; |
| 41 | + console.log('restored', methodName); |
| 42 | + console.log('digest cycle ran', count, 'time(s) during', name); |
| 43 | + }); |
| 44 | + }); |
| 45 | + }; |
| 46 | + console.log('wrapped', name, 'for measuring number of digest cycles'); |
| 47 | + |
| 48 | +}()); |
0 commit comments