Automatically Unbind Events When $scope Is Destroyed

June 27, 2015 angularjs, javascript | Comments

During daily development I runs into specific problem with unbinding events. Along with application growth I had a lot of events to removed. To do it we can write simply code e.g:

1
2
3
4
5
var eventDeregistrationFn = $scope.$on('name', callback);

$scope.$on('$destroy', function () {
  eventDeregistrationFn();
});

And it’s done. We can simply deregistrate event. How it exatly works? Let’s take a quick look at Angular core code:

1
2
3
4
5
6
7
8
9
10
$on: function(name, listener) {
  (...)
  return function() {
    var indexOfListener = namedListeners.indexOf(listener);
    if (indexOfListener !== -1) {
      namedListeners[indexOfListener] = null;
      decrementListenerCount(self, 1, name);
    }
  };
},

Function $on which is used to register listeners returns another function. Inside body of it is set namedListeners[indexOfListener] to null which means that callback of event is removed. And that’s all event is unbinded.

Everything is great if we have one, two or max three such events to deregister. But when we have them more and more? duplicating code $scope.$on(‘$destroy’) is very inefficient. I don’t want to take care about deregistering events and I want to automate this process. But how? today I figured out that I can create simply service which will handle two main behaviours: registration and deregistration events. I wrote simply service, so simply that I was afraid to publish it here ;)

1
2
3
4
5
6
7
8
9
10
11
12
13
(function () {
  var app = angular.module('App.Main');

  app.service('EventService', function () {
      this.on = function ($scope, name, listener) {
          var deregistrationFn = $scope.$on(name, listener);

          $scope.$on('$destroy', function () {
              deregistrationFn();
          });
      }
  });
})();

and example of usage:

1
EventService.on($scope, 'name', callback);

that’s all! I don’t need to include created event into $destroy event. It’s done by EventService.

If you have some comments feel free to write them below. Cheers.

Compability

Angular
Tested on: Angular 1.3.15

Comments