简体   繁体   English

eslint警告解释

[英]eslint warning interpretation

I've been playing around a bit with ES6 and angular and I'm using eslint-plugin-angular to validate my javascript. 我一直在玩ES6和角度,我使用eslint-plugin-angular来验证我的javascript。 I have the following service: 我有以下服务:

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

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

But eslint gives me the following error: 但是eslint给了我以下错误:

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

I mean I understand the warning, but I've never done this in my previous angular projects, should I have done what the error suggests? 我的意思是我理解这个警告,但是我在以前的角度项目中从未这样做过,如果我做了错误建议的话? Why is it needed/good practice? 为什么需要/良好实践?

The docs for eslint-plugin-angular reference John Papa's angular styleguide , but I didn't really find a mention of this situation there. eslint-plugin-angular参考文献John Papa的角度风格指南 ,但我并没有真正提到这种情况。

Not only does the johnpapa styleguide not mention this situation, it actually includes an example of ignoring the return of $rootScope.$on . johnpapa样式指南不仅没有提到这种情况,它实际上还包括一个忽略$rootScope.$on的返回的例子。 However, the discussion on one of the eslint-plugin-angular issues clarifies the intent a little bit: 然而,关于其中一个eslint-plugin-angular问题的讨论澄清了一点意图:

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. 如果控制器在$rootScope上注册一个监听器,它应该在“ $destroy ”中手动销毁,因为根作用域将比所有控制器寿命更长。 -- davidmason - davidmason

That post also indirectly references the "Directives should clean up after themselves" best practice from the AngularJS documentation . 该帖子还间接引用了AngularJS文档中的“指令应该自行清理”的最佳实践。

So bottom line: A regular $scope object will eventually be destroyed when its controller does, and take its event listeners with it (assuming you haven't done any kind of circular referencing that keeps it in scope). 所以底线:一个普通的$scope对象最终将在其控制器执行时被销毁,并将其事件监听器与它一起使用(假设您没有进行任何类型的循环引用,使其保持在范围内)。 $rootScope never dies, and therefore never releases its event handlers. $rootScope永远不会死,因此永远不会释放它的事件处理程序。 If your controller is adding an event listener to $rootScope , it should remove that handler in your controller's $destroy handler. 如果你的控制器正在向$rootScope添加一个事件监听器,它应该在你的控制器的$destroy处理程序中删除该处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM