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

2

12

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.

Honkytonk answered 21/12, 2013 at 3:33 Comment(0)
F
18

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.

Finance answered 21/12, 2013 at 16:17 Comment(2)
And the scope is destroyed... when? When the html block, to which the controller is attached, is replaced by something else?Cay
Although you might not destroy your scope explicitly, when a parent scope gets destroyed, it and its children no longer participate in the $digest cycle. Particularly, watchers are not called, events do not reach. And if elements disappear from a page it's probably safe to assume that some parent scope got destroyed. You can experiment with it here.Cay
M
1

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.).

Monochord answered 21/12, 2013 at 7:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.