angular.js $destroy 事件 - 我应该手动解除绑定吗? [英] angular.js $destroy event - should I manually unbind?

查看:19
本文介绍了angular.js $destroy 事件 - 我应该手动解除绑定吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚 angular base 是否会自动解除绑定观察者和作用域事件与 $scope.$on(...)$scope.$watch(...) 当范围被销毁时?

I'm trying to figure out if angular base automatically unbinds watchers and scope events bound with $scope.$on(...) or $scope.$watch(...) when scope is destroyed?

假设我有以下代码:

$scope.$on('someEvents', handleSomeEvent);
$scope.$watch('someProperty', handleSomePropertyChange);

在作用域上触发 $destroy 事件时,是否需要手动解除这些观察者和事件的绑定?

Do I need to manually unbind these watchers and events when $destroy event is triggered on scope?

推荐答案

根据 Angular 文档<代码>$scope:

'$destroy()' 当希望作用域及其子作用域与父作用域永久分离时,必须在作用域上调用'$destroy()',从而通过调用停止参与模型更改检测和侦听器通知.

'$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() 被调用时,所有的观察者和监听器都会被移除,并且代表作用域的对象变得有资格进行垃圾收集.

So it seems when $destroy() is called all the watchers and listeners get removed and the object which represented the scope becomes eligible for garbage collection.

如果我们查看 destroy() 源代码 我们会看到一行:

If we look at the destroy() source code we'll see a line :

forEach(this.$$listenerCount, bind(null, decrementListenerCount, this));

应该删除所有侦听器.

正如@glepretre 所提到的,它适用于控制器中的观察者和监听者.上面列出的同一个文档页面说:

As mentioned by @glepretre it applies to the watchers and listeners in the controller. The same doc page listed above says that:

请注意,在 AngularJS 中,还有一个 $destroy jQuery 事件,可用于在元素从 DOM 中删除之前清理 DOM 绑定.

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 事件并自己做必要的清理

So if you have specific listeners in the directives you should listen to the $destroy event and do the necessary cleanup yourself

这篇关于angular.js $destroy 事件 - 我应该手动解除绑定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆