How to avoid memory leaks using angularjs-nvd3-directives

后端 未结 3 860
闹比i
闹比i 2021-02-04 08:43

I\'m working on an angularjs application using angularjs-nvd3-directives to render charts.

After a check with Chrome Developer Tools, I detected some memory leaks linked

相关标签:
3条回答
  • 2021-02-04 08:57

    You might forget to remove window resize listeners.

    angularApp.run(function($rootScope) {
      $rootScope.$on('$routeChangeStart', function(event, next, current) {
        if (typeof(current) !== 'undefined'){
            //destroy d3 stuff 
            window.nv.charts = {};
            window.nv.graphs = [];
            window.nv.logs = {};
    
            // and remove listeers for onresize. 
            window.onresize = null;
        }
      });
    }); 
    

    Also you can try removing whole svg element but it doesn't seem to be the best way.

    0 讨论(0)
  • 2021-02-04 09:02

    I recommend that you move your graph to your own directives that will hold the nvd3 directives on their templates and listen on each directive for scope.

    $destroy also destroy the element on this event.

    Controllers should retrieve the data and assign them to the directive.

    You may be want to listen to the $routeChangeStart on the directive, so the cleaning will be encapsulated on the part that use the data. This way you will avoid duplicate code.

    I use this techniques to clean my directives that use modals so i don't have duplicate events listeners or ids.

    0 讨论(0)
  • 2021-02-04 09:24

    There is a similar issue at the github: https://github.com/cmaurer/angularjs-nvd3-directives/issues/193

    As I explained there the following worked better:

      $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
    angular.element(document.body.querySelectorAll('.nvd3')).remove();
    

    This solves the SVG memory leaks. But still there are some memory leaks on the data side (Array).

    0 讨论(0)
提交回复
热议问题