When is it necessary to manually unbind a watcher?

(I'm using Angular 1)

I have an array of complex objects. I have a watch bound to something like this:

myArray[objectId].propArr.length

if the object myArray[objectId] is deleted, what happens to the watch? Will I need to manually unbind it? Will it automagically get cleaned up since the object no longer exists?

Posted Apr 29, 2019, 5:53 PM UTC

86
Koaty•

I’m on my phone on a fishing trip a few beers in, but I think this is what you want. The result of a scope watch is a function that can unwind the watcher. Cheers!

var unregister = $scope.watch(‘prop’, function () {

If(something) { unregister(); }

});

5
linuxlassOP•

Thanks, you saved me a stackOverflow lookup :) I hope the fish are/were biting...

1
Koaty•

Ill be having salmon for weeks, glad I could help 😉

3
luckiem•

You only need to manually unbind when watching on $rootScope actually. If you create a watch on the local $scope of a component/controller, the watches are automatically removed when the component/controller is destroyed, i.e. when $scope.$on('$destroy') fires.

(Watches are not unbound when the array/object pointing to it is unreferenced though. Hence the need to unbind manually, but only if you're using $rootScope)

3
linuxlassOP•

Thank you, this helps a lot!

1
[deleted]•

[removed]

1