如何避免内存泄漏使用angularjs-nvd3-指令 [英] How to avoid memory leaks using angularjs-nvd3-directives

查看:1233
本文介绍了如何避免内存泄漏使用angularjs-nvd3-指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用angularjs-nvd3-指令来生成图表的angularjs应用程序。

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

使用Chrome开发者工具的检查后,我发现挂图表一些内存泄漏。当用户浏览含有图表不同意见的内存空间还没有完全释放。

After a check with Chrome Developer Tools, I detected some memory leaks linked to the charts. When the user navigates through different views containing charts the memory is never fully released.

我已经在做的图形控制器一些清理工作:

I'm already doing some cleanup on the graphs controllers:

$scope.$on('$destroy', function() {
  d3.select( '#exampleId' ).remove();
  d3.select( '#exampleId2' ).remove();
  ...
});

和上routeChange事件:

And on the routeChange event:

myApp.run(function($rootScope, $templateCache) {
  //try to clear unused objects to avoid huge memory usage
  $rootScope.$on('$routeChangeStart', function(event, next, current) {
    if (typeof(current) !== 'undefined'){
      //destroy all d3 svg graph
      d3.selectAll('svg').remove();
      nv.charts = {};
      nv.graphs = [];
      nv.logs = {};
    }
  });
});

当我从我的应用程序中删除图表,内存使用率一直追溯到初始值。

When I remove the charts from my app, the memory usage always goes back to the initial value.

通过图:

内部消除:

With the graph: Whithout:

是否有任何其他方式来释放这些图表生成的内存?

Is there any other way to release memory generated by those charts ?

的jsfiddle 来证明这个问题。

推荐答案

您可能会忘记删除窗口调整监听器。

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;
    }
  });
}); 

您也可以尝试删除整个SVG元素,但它似乎并没有是最好的方式。

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

这篇关于如何避免内存泄漏使用angularjs-nvd3-指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆