Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to "unwatch" scope variables when the scope is being destroyed?

Below are the docs from angular. I'm watching several variables that are part of this scope to build up a filter string for ng-grid. When this scope is being destroyed, do I NEED to unwatch them by calling the return value from $scope.$watch, or is the destruction of the scope enough to deal with that? What if the variables being watched were NOT part of this scope?

Will I leak memory/cause performance problems if I don't "unwatch" variables that are being destroyed along with the scope.


$destroy()

Removes the current scope (and all of its children) from the parent scope. Removal implies that calls to $digest() will no longer propagate to the current scope and its children. Removal also implies that the current scope is eligible for garbage collection.

The $destroy() is usually used by directives such as ngRepeat for managing the unrolling of the loop.

Just before a scope is destroyed, a $destroy event is broadcasted on this scope. Application code can register a $destroy event handler that will give it a chance to perform any necessary cleanup.

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.

like image 482
boatcoder Avatar asked Dec 21 '13 03:12

boatcoder


2 Answers

I also think that this should be explicitely explained in the documentation. I've deduced that unwatching was unnecessary from the angular source code which always ignores the result of scope.$watch (in ngIf, ngShow, ngRepeat, etc.).

like image 29
JB Nizet Avatar answered Sep 22 '22 17:09

JB Nizet


A quick look at the source code will show you that the removal function returned by $watch doesn't do anything exotic. It simply removes an item from the scope.$$watchers array.

As such, once the scope is destroyed, the entire array goes with it, and the garbage collector will clean everything up for you.

Regardless of what you are watching, the watch itself is stored in the scope. Which is why, that in order to use $watch, you don't call angular.$watch, but rather you call $scope.$watch.

like image 84
Noishe Avatar answered Sep 21 '22 17:09

Noishe