javascript 如何在 Angular 中解除 $on 的绑定?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23424381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:51:16  来源:igfitidea点击:

How to unbind $on in Angular?

javascriptangularjsjavascript-events

提问by jcubic

I have a code that use $scope.$on one time on init and then in a function, so the code is executed multiple times. How can I unbind if first before I bind it again. I've try $scope.$off but there's not such function, docs.angularjs.org/api say nothing about $on. I'm using angular 1.0.6.

我有一个代码在 init 上使用 $scope.$ 一次,然后在一个函数中使用,所以代码被执行多次。在我再次绑定之前,我如何解除绑定。我试过 $scope.$off 但没有这样的功能,docs.angularjs.org/api 对 $on 一无所知。我正在使用 angular 1.0.6。

回答by suneetha

If you don't un-register the event, you will get a memory leak, as the function you pass to $on will not get cleaned up (as a reference to it still exists). More importantly, any variables that function references in its scope will also be leaked. This will cause your function to get called multiple times if your controller gets created/destroyed multiple times in an application. Fortunately, AngularJS provides a couple of useful methods to avoid memory leaks and unwanted behavior:

如果您不取消注册该事件,则会出现内存泄漏,因为您传递给 $on 的函数不会被清除(因为对它的引用仍然存在)。更重要的是,函数在其范围内引用的任何变量也将被泄漏。如果您的控制器在应用程序中被多次创建/销毁,这将导致您的函数被多次调用。幸运的是,AngularJS 提供了一些有用的方法来避免内存泄漏和不需要的行为:

  • The $on method returns a function which can be called to un-register the event listener.
  • Whenever a scope gets cleaned up in Angular (i.e. a controller gets destroyed) a $destroy event is fired on that scope. You can register to $scope's $destroy event and call your cleanUpFunc from that.
  • $on 方法返回一个函数,可以调用该函数来取消注册事件侦听器。
  • 每当 Angular 中的作用域被清理(即控制器被销毁)时,就会在该作用域上触发 $destroy 事件。您可以注册 $scope 的 $destroy 事件并从中调用您的 cleanUpFunc。

See the documentation

查看文档

Sample Code:

示例代码:

   angular.module("TestApp")
      .controller("TestCtrl",function($scope,$rootScope){
        var cleanUpFunc = $scope.$on('testListener', function() {
          //write your listener here
        });

       //code for cleanup
       $scope.$on('$destroy', function() {
         cleanUpFunc();
        };      
    })

回答by phylax

$scope.$onreturns a function which you can call to unregister.

$scope.$on返回一个函数,您可以调用它来取消注册。