Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

javascript - Do you need to unbind $scope.$on in $scope $destroy event?

I have directive that bind event using $on do I need to remove that binding when scope is destroyed, or is it done automatically? Also do I need to call $element.off?

return {
    restrict: 'A',
    link: function($scope, $element, $attrs) {
        $element.on('load', function() {
            $element[0].contentWindow.focus();
        });
        $scope.$on('iframe:focus', function() {
            $element[0].contentWindow.focus();
        });
    }
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$scope.$on() listenerers will be destroyed / cleaned up automatically when it loses its representation due to E2E binding in your view. Note that this will not happen for $rootScope.$on() bindings. You could also take a look at the $scope documentation of AngularJS.

Answer in a few words:

  • $scope.$on(); will be destroyed automatically.
  • You need to destroy $rootScope.$on() manually.

The documenation says:

Scope Destruction - When child scopes are no longer needed , it is the responsibility of the child scope creator to destroy them via scope.$destroy() API. This is done in order to stop propagation of $digest calls into the child scope and allow for memory used by the child scope models to be reclaimed by the garbage collector.

Example of how to destroy $rootScope.$on():

//bind event
var registerScope = $rootScope.$on('someEvent', function(event) {
    console.log("fired");
});

// clean up
$scope.$on('$destroy', registerScope);

This plnkr will show you the different behaviors of $scope.$on() and $rootScope.$on().

By switching the view in this plunkr the controller will be rebinded to your view. The $rootScope.$on(); event is binded every time you switch a view without destroying the event bindings of the view before. In that way the $rootScope.$on() listeners will be stacked/multiplied. This will not happen to the $scope.$on() bindings because it will be destroyed by switching the view (losing the E2E binding representation in DOM).


Note that:

  • $scope.$on('event'); will listen to $scope.$broadcast('event') & $rootScope.$broadcast('event')

  • $rootScope.$on('event'); will only listen to $rootScope.$broadcast('event')


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...