optimization - AngularJS: Pause $digest & watchers on hidden DOM elements -
we're building single page application has multiple pages loaded tabs. content of 1 tab visible @ given time (much browser), want temporarily pause $digest
, watchers executing on dom nodes of hidden tabs, until user switches tab.
is there way achieve this, model continues updated background tabs, view updates based on condition.
the following code illustrates problem:
<div ng-repeat="tab in tabs" ng-show="tab.id == current_tab.id"> <!-- tab content bindings --> </div>
the goal optimization.
i'm aware of scalyr directives, want more specific solution without features contained in scalyr.
after trial , error i've figured out following directive pauses children's $$watchers
if expression on attribute evaluates true
, on false
restores backed $$watchers
app.directive('pausechildrenwatchersif', function(){ return { link: function (scope, element, attrs) { scope.$watch(attrs.pausechildrenwatchersif, function (newval) { if (newval === undefined) { return; } if (newval) { togglechildrenwatchers(element, true) } else { togglechildrenwatchers(element, false) } }); function togglechildrenwatchers(element, pause) { angular.foreach(element.children(), function (childelement) { toggleallwatchers(angular.element(childelement), pause); }); } function toggleallwatchers(element, pause) { var data = element.data(); if (data.hasownproperty('$scope') && data.$scope.hasownproperty('$$watchers') && data.$scope.$$watchers) { if (pause) { data._bk_$$watchers = []; $.each(data.$scope.$$watchers, function (i, watcher) { data._bk_$$watchers.push($.extend(true, {}, watcher)) }); data.$scope.$$watchers = []; } else { if (data.hasownproperty('_bk_$$watchers')) { $.each(data._bk_$$watchers, function (i, watcher) { data.$scope.$$watchers.push($.extend(true, {}, watcher)) }); } } } togglechildrenwatchers(element, pause); } } } });
Comments
Post a Comment