angular.js $destroy event - should I manually unbind?

Vytautas Butkus picture Vytautas Butkus · Mar 4, 2014 · Viewed 22k times · Source

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?

Answer

Igor Malyk picture Igor Malyk · Mar 4, 2014

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