Should angular $watch be removed when scope destroyed?

前端之家收集整理的这篇文章主要介绍了Should angular $watch be removed when scope destroyed?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

$scope上的watchers和listeners在$scope destroy的时候是否需要手动unregister

这里有讨论: http://stackoverflow.com/questions/25113884/should-angular-watch-be-removed-when-scope-destroyed

结论是: No,you don't need to remove $$watchers,since they will effectively get removed once the scope is destroyed.

From Angular's source code (v1.2.21),Scope's $destroy method:

$destroy: function() {
    ...
    if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
    if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
    if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
    if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
    ...
    this.$$watchers = this.$$asyncQueue = this.$$postDigestQueue = [];

So,the $$watchers array is emptied (and the scope is removed from the scope hierarchy).

Removing the watcher from the array is all the unregister function does anyway:

$watch: function(watchExp,listener,objectEquality) {
    ...
    return function deregisterWatch() {
        arrayRemove(array,watcher);
        lastDirtyWatch = null;
    };
}

So,there is no point in unregistering the $$watchers "manually".

You should still unregister event listeners though (as you correctly mention in your post) !

NOTE: You only need to unregister listeners registered on other scopes. There is no need to unregister listeners registered on the scope that is being destroyed. E.g.:

// You MUST unregister these
$rootScope.$on(...);
$scope.$parent.$on(...);

// You DON'T HAVE to unregister this
$scope.$on(...)

(Thx to @John for pointing it out)

Also,make sure you unregister any event listeners from elements that outlive the scope being destroyed. E.g. if you have a directive register a listener on the parent node or on,then you must unregister them too. Again,you don't have to remove a listener registered on the element being destroyed.

Kind of unrelated to the original question,but now there is also a $destroyed event dispatched on the element being destroyed,so you can hook into that as well (if it's appropriate for your usecase):

link: function postLink(scope,elem) {
  doStuff();
  elem.on('$destroy',cleanUp);
}

猜你在找的Angularjs相关文章