sourcetip

Angular JS 디렉티브 $destroy

fileupload 2023. 3. 19. 18:24
반응형

Angular JS 디렉티브 $destroy

각진 앱 설정이 있습니다.ng-view하나의 뷰에는 뷰 자체 외에 동적으로 로드되는 컴포넌트도 있습니다.이 컴포넌트는 콘텐츠를 컴파일하여 다른 디렉티브(즉, 다른 디렉티브)와 연계할 수 있도록 하는 명령어입니다.해당 컴포넌트 내의 콘텐츠는 다음과 같이 컴파일됩니다.$compile(element.contents())(scope);.

예를 들어 다음과 같습니다.

<ng-view>
  <viewer doc="getDocument()">
  </viewer>
</ng-view>
angular.directive('viewer', ['$compile', '$anchorScroll', function($compile, $anchorScroll) {
  return function(scope, element, attrs) {
    scope.$watch(
      function(scope) {
        var doc = scope.$eval(attrs.doc);
        if (!doc)
          return ""
        return doc.html;
      },
      function(value) {
        element.html(value);
        $compile(element.contents())(scope);
      }
    );
  };
}]);

문제는 루트를 바꿀 때 기본적으로 루트를 바꿀 수 있다는 것입니다.ng-view또는viewer의 내용입니다.제가 겪고 있는 문제는 메모리 누수입니다. 메모리 누수는 다른 방향에서viewer루트가 변경되어도 청소하지 않습니다.

예를 들어 다음과 같습니다.

angular.directive('i18n', ['$rootScope', 'LocaleService', function($rootScope, LocaleService) {
  var cleanup;
  return {
    restrict: 'EAC',
    compile: function(element, attrs) {
      var originalText = element.text();
      element.text(LocaleService.getTranslation(originalText, attrs.locale));
      cleanup = $rootScope.$on('locale-changed', function(locale) {
        element.text(LocaleService.getTranslation(originalText, attrs.locale || locale));
      });
    },
    link: function(scope) {
      scope.$on('$destroy', function() {
        console.log("destroy");
        cleanup();
      });
    }
  };
}]);

이러한 이벤트를 적절하게 정리하려면 어떻게 해야 합니까?

당신이 제시한 i18n의 예는 한번만 사용한다면 효과가 있을 것입니다.

컴파일 함수 안에서 이벤트 바인딩을 하면 안 될 것 같아요.대신 링크 함수 내에서 수행할 수 있습니다.

angular.directive('i18n', ['$rootScope', 'LocaleService', function($rootScope, LocaleService) {
  return {
    restrict: 'EAC',
    link: function(scope, element, attrs) {
      var cleanup;
      var originalText = element.text();
      element.text(LocaleService.getTranslation(originalText, attrs.locale));
      cleanup = $rootScope.$on('locale-changed', function(locale) {
        element.text(LocaleService.getTranslation(originalText, attrs.locale || locale));
      });
      scope.$on('$destroy', function() {
        console.log("destroy");
        cleanup();
      });
    }
  };
}]);

또는 이벤트를 자 스코프 자체에서 바인드하여$broadcast에서$rootScope작동시킬 수 있습니다.이렇게 하면 스코프가 파괴되면 이벤트가 자동으로 수집됩니다.

angular.directive('i18n', ['$rootScope', 'LocaleService', function($rootScope, LocaleService) {
  return {
    restrict: 'EAC',
    link: function(scope, element, attrs) {
      var originalText = element.text();
      setElText();
      function setElText(locale){
        element.text(LocaleService.getTranslation(originalText, attrs.locale || locale));
      }
      scope.$on('locale-changed', setElText);
    }
  };
}]);

$rootScope.$broadcast('locale-change', 'en-AU');

언급URL : https://stackoverflow.com/questions/17203005/angularjs-directive-destroy

반응형