Is it safe to unsubscribe from all events in the area. $ Destroy?

I found the AngularJS directive that looks like this:

function MyDirective() {
    return {
        restrict: 'A',
        link: function(scope, elem) {
            elem.on('click', function() {
                // do stuff
            });
            scope.$on('$destroy', function () {
                elem.off('click');
            });
        }
    };
}

I am particularly concerned about the following part:

elem.off('click');

Can we assume that after the scope.$destroyelement will no longer be used, and we can just clear all listeners , and not just those added by this particular directive?

+4
source share
2 answers

, , . IMHO . , click, . .

function MyDirective() {
    return {
        restrict: 'A',
        link: function(scope, elem) {
            elem.on('click', function() {
                // do stuff
            });
            scope.$on('$destroy', function () {
                elem.off('click');
            });
        }
    };
}

, , , , , , , , , , , click . , , , namespace , :

//Subscribing
angular.element("#element")
  .on("click.myNamespace", function() { 
     console.log("doSomething");
   });
//Unsubscribing
$("#element").off("click.myNamespace");

CSS , namespacing, jQuery, .

+1

. , , . $() API. , $digest , , .

, , , DOM node, , .

angular.element https://docs.angularjs.org/api/ng/function/angular.element

, AngularJS directives ( ng-click/`ng-change'/....)

ng-... . / $destroy.

. , ( ), scope . (ng-controller), destroyed, . , Angular ...

+2

Source: https://habr.com/ru/post/1669264/


All Articles