toddmotto / angularjs-styleguide

AngularJS styleguide for teams
https://ultimateangular.com
5.96k stars 700 forks source link

question about the way to unbind multiple listeners on $destroy #35

Closed royling closed 9 years ago

royling commented 9 years ago

In event pub/sub section, why do we unbind listener within multiple $destroy event binding?

var rootListeners = {
  'customEvent1': $rootScope.$on('customEvent1'[, callback]),
  'customEvent2': $rootScope.$on('customEvent2'[, callback]),
  'customEvent3': $rootScope.$on('customEvent3'[, callback])
};
for (var unbind in rootListeners) {
  $scope.$on('$destroy', rootListeners[unbind]);
}

Can we do this instead? move for loop into the $destroy event handler

$scope.$on('$destroy', function() {
  for (var unbind in rootListeners) {
    rootListeners[unbind]();
  }
});
stephnr commented 9 years ago

I like this idea better. The original looks like I am attaching unique handlers to each rootListener. Why not just one catch all?

toddmotto commented 9 years ago

Just updated it, I've been using an Array instead of Object lately, so added this syntax:

    var unbind = [
      $rootScope.$on('customEvent1'[, callback]),
      $rootScope.$on('customEvent2'[, callback]),
      $rootScope.$on('customEvent3'[, callback])
    ];
    $scope.$on('$destroy', function () {
      unbind.forEach(function (fn) {
        fn();
      });
    });