【问题标题】:Angular.js - will this directive cause a memory leak?Angular.js - 这个指令会导致内存泄漏吗?
【发布时间】:2014-06-03 13:05:35
【问题描述】:

我在下面有一个指令,想知道当组件从 DOM 中删除时这是否会导致内存泄漏。 Angular 在“幕后”做了很多事情,我不知道 JS/Angular GC 是否会处理这个问题。 (而且我仍在尝试理解 Chrome 工具中的 JS Profiler 以便能够自己解决这个问题)。那么,有这种经验的人可以回答这个问题吗?

angular.module('myApp')
    .directive('myDir', [function() {
        return {
            restrict: 'AE',
            replace: true,
            scope: {
                 someEvent:'@'
            },
            transclude: 'element',
            template: function(tElement, tAttrs) {
                return '<div class="">' +
                    '<div ng-transclude ng-click="blah()" class=""></div>'
                    '</div>';
            },
            link: function (scope, el) {  

                scope.doSomething = function(){
                  .....
                }

               scope.$on(scope.someEvent, scope.doSomething);                             

            }
        }
    }]);

当从 dom 中删除元素时,上面的代码会导致内存泄漏吗?我的意思是我知道我可以轻松地增强它来添加一个 $destroy 事件:IE:

var unregister = scope.$on(scope.someEvent, scope.doSomething);  
 scope.$on("$destroy",function() {
          unregister();                    
});

但是这个额外的步骤是必要的还是 Angular 会处理这个问题?

感谢您的帮助!

【问题讨论】:

    标签: angularjs memory-management angularjs-directive


    【解决方案1】:

    您不需要执行该步骤,当作用域被销毁时,其上的所有侦听器也将被销毁。

    【讨论】:

    • 只有 $on 会被清理。任何 jQuery.on 调用都必须自己清理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多