gpt4 book ai didi

javascript - eslint警告解释

转载 作者:数据小太阳 更新时间:2023-10-29 04:38:25 25 4
gpt4 key购买 nike

我一直在玩 ES6 和 angular,我正在使用 eslint-plugin-angular 来验证我的 javascript。我有以下服务:

export function runBlock ($rootScope, $state, $log) {
'ngInject';

$rootScope.$on( '$stateChangeStart', function(event, toState) {
// ...
} );

但是 eslint 给我以下错误:

The "$on" call should be assigned to a variable, in order to be
destroyed during the $destroy event

我的意思是我理解这个警告,但是我在以前的 Angular 项目中从来没有这样做过,我应该按照错误提示去做吗?为什么需要/良好实践?

eslint-plugin-angular 引用文档 John Papa's angular styleguide , 但我并没有在那里真正找到这种情况的提及。

最佳答案

johnpapa styleguide 不仅没有提到这种情况,它实际上包括一个忽略返回的例子$rootScope.$on。然而,关于one of the eslint-plugin-angular issues的讨论稍微澄清一下意图:

If a controller is registering a listener on $rootScope it should probably be manually destroyed in "$destroy" since root scope will outlive all the controllers. --davidmason

该帖子还间接引用了来自 the AngularJS documentation 的“指令应该自行清理”最佳实践。 .

所以底线:一个常规的 $scope 对象最终会在它的 Controller 被销毁时被销毁,并带走它的事件监听器(假设你没有做任何类型的循环引用来保持它在适用范围)。 $rootScope 永远不会消亡,因此永远不会释放它的事件处理程序。如果您的 Controller 正在向 $rootScope 添加事件监听器,它应该在您的 Controller 的 $destroy 处理程序中删除该处理程序。

关于javascript - eslint警告解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33081407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com