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

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

问题描述

我试图找出如果角座可自动解除绑定与 $范围内绑定观察家和范围的事件。在$(...) $范围。$腕表(...)时,范围为摧毁

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?

假设我有以下code:

Suppose I have following code:

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

我是否需要手动解除这些观察家当$破坏事件的事件触发的范围是什么?

Do I need to manually unbind these watchers and events when $destroy event is triggered 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.

如此看来,当 $摧毁()被称为所有的观察者和听众得到去除并重新$ P $对象psented范围变得符合垃圾收集

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() source code 我们将看到一行:

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

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

这是应该去掉所有的听众。

Which is supposed to remove all the listeners.

正如@ GLE pretre它适用于控制器中的观察者和听众提及。上述相同的文档页说:

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

请注意的是,在AngularJS,也有一个$破坏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.

所以,如果你的指令有特定的听众,你应该听 $摧毁事件,并自己做必要的清理

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

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

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