2016-01-28 117 views
0

我正在为客户端开发一个巨大的项目,所以为了使代码更清洁,我正在做一些返工。我在这部分代码:角度事件监听器

var removeListener = $rootScope.$on('logoutEvent', function() { 
    changedAttribut = EditorialContentService.getChangedAttribut($scope.promotion, OLDPromo, hasUploadImage); 
    if (changedAttribut.length < 1) { 
     $rootScope.canClose = true; 
    } else { 
     $rootScope.canClose = false; 
    } 
}); 
$scope.$on("$destroy", removeListener); 

的事情,是的,我需要把代码中的服务或一个工厂或任何其他建议,内避免重复,因为它是在许多控制器使用。

回答

0

无论是拨打电话(而不是$范围)

$rootScope.$on("$destroy", removeListener); 

,这将删除侦听器时整个应用程序被破坏(但不是真正需要的,因为事件与$何时范围被自动删除注册他们被登记在被破坏), 或暴露在工厂移除侦听器的功能,并调用它的时候适当范围破坏:

// inside the factory 
return { 
    destroy: function() { 
     removeListener(); 
    } 
}; 

// inside the appropriate controller 
$scope.$on('$destroy', thatFactory.destroy); 
+0

这不是正是我想要的,但它是有用的 – 3tmaan