修复Angular内存泄漏

Fixing Angular memory leaks

本文关键字:泄漏 内存 Angular 修复      更新时间:2023-09-26

我正在尝试优化我的Angular应用程序,并浏览了几个网站,我也发现了这种做法:

var cleanup = $scope.$on('someEvent', function() {  
    $scope.refresh();
});
$scope.$on('$destroy', function() {
    cleanup();
});

由于我的控制器中有几个$scope.$on,我想知道这样使用它是否正确:

var first = $scope.$on('firstEvent', function() {  
    $scope.something1();
});
var second = $scope.$on('secondEvent', function() {  
    $scope.something2();
});
var third = $scope.$on('thirdEvent', function() {  
    $scope.something3();
});
$scope.$on('$destroy', function() {
    first();
    second();
    third();
});

这是否便于实施和纠正?

正如引用的文章所说,

如果你忘记了,Angular应该清理它,但建议总是自己做。

围绕预期的框架行为制定保障措施过于谨慎,很难被称为良好做法。

而jQuery/jqLite(element.on)和第三方事件侦听器可能会导致内存泄漏,应在作用域$destroy元素$destroy事件上进行清理。