javascript - angular.js $destroy 事件 - 我应该手动解除绑定(bind)吗?

标签 javascript angularjs angularjs-scope

我想弄清楚 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/

相关文章:

angularjs - Angular 范围函数多次执行

javascript - 如何在没有Google SDK的情况下使用key脚本在angularjs中使用谷歌地图

javascript - 如何访问 Angular.JS 中 $routeProvider 配置中的工厂数据对象?

angularjs - 测试 modalInstance.result.then

javascript - Angular 空选项删除

javascript - 单击时切换灯箱中的可见区域。 Angular 和 JQuery

javascript - Rails Kaminari 示例无限滚动不起作用

javascript - Angular 使用静态文件加载器翻译默认语言

javascript - Meteor 0.9 模数部署不起作用 - "Cannot find module ' 纤维'”

javascript - AngularJS 一次只显示一个列表项