Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to figure out if angular base automatically unbinds watchers and scope events bound with $scope.$on(...) or $scope.$watch(...) when scope is destroyed?

Suppose I have following code:

$scope.$on('someEvents', handleSomeEvent);
$scope.$watch('someProperty', handleSomePropertyChange);

Do I need to manually unbind these watchers and events when $destroy event is triggered on scope?

See Question&Answers more detail:os

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

1 Answer

According to Angular documentation on $scope:

'$destroy()' must be called on a scope when it is desired for the scope and its child scopes to be permanently detached from the parent and thus stop participating in model change detection and listener notification by invoking.

Also

Removal also implies that the current scope is eligible for garbage collection.

So it seems when $destroy() is called all the watchers and listeners get removed and the object which represented the scope becomes eligible for garbage collection.

If we look at the destroy() source code we'll see a line :

forEach(this.$$listenerCount, bind(null, decrementListenerCount, this));

Which is supposed to remove all the listeners.

As mentioned by @glepretre it applies to the watchers and listeners in the controller. The same doc page listed above says that:

Note that, in AngularJS, there is also a $destroy jQuery event, which can be used to clean up DOM bindings before an element is removed from the DOM.

So if you have specific listeners in the directives you should listen to the $destroy event and do the necessary cleanup yourself


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...