我想弄清楚 Angular Base 是否会自动解除与 $scope.$on(...)
或 $scope.$watch(.. .)
当作用域被销毁时?
假设我有以下代码:
$scope.$on('someEvents', handleSomeEvent);
$scope.$watch('someProperty', handleSomePropertyChange);
在范围内触发 $destroy 事件时,是否需要手动取消绑定(bind)这些观察者和事件?
最佳答案
根据 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.
还有
Removal also implies that the current scope is eligible for garbage collection.
所以看起来当 $destroy()
被调用时,所有观察者和监听者都被移除,代表范围的对象变得有资格进行垃圾收集
。
如果我们看一下 destroy()
source code我们会看到一行:
forEach(this.$$listenerCount, bind(null, decrementListenerCount, this));
应该移除所有的监听器。
如@glepretre 所述,它适用于 Controller 中的观察者和听众。上面列出的同一文档页面说:
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.
因此,如果您在指令中有特定的监听器,您应该监听 $destroy
事件并自己进行必要的清理
关于javascript - angular.js $destroy 事件 - 我应该手动解除绑定(bind)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22169888/