Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unbind $on in Angular?

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, https://docs.angularjs.org/api say nothing about $on. I'm using angular 1.0.6.

like image 214
jcubic Avatar asked May 02 '14 08:05

jcubic


2 Answers

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:

  • 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.

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();
        };      
    })
like image 75
suneetha Avatar answered Sep 17 '22 22:09

suneetha


$scope.$on returns a function which you can call to unregister.

like image 44
phylax Avatar answered Sep 17 '22 22:09

phylax