I am currently working on structuring the events within a service to enable a mechanism for subscribing/unsubscribing listeners when a controller's scope is terminated. Previously, I utilized $rootScope.$on
in this manner:
if(!$rootScope.$$listeners['event']) {
$rootScope.$on('event', function(ev, data){
// perform some actions...
});
}
or
$scope.$on('$destroy', function(ev, data){
// unsubscribe the listener
});
To ensure that only one listener exists for each event, it is crucial to remove the listener when the corresponding controller is no longer active; otherwise, the registered function would still be executed.
Therefore, I aim to introduce a $destroy
event listener within my controller to eliminate the listener upon scope destruction without repeating this process for every event creation. This motivates me to create a specialized service for encapsulating these events.
angular.module('core').factory('event', [
function() {
var service = {};
service.events = {};
service.on = function(scope, eventId, callback) {
scope.$on('$destroy', function(ev, other){
//unsubscribe
});
service.events[eventId] = callback;
// scope = null; perhaps?
};
service.emit = function(eventId, data){
if (service.events[eventId])
service.events[eventId](data);
else
return new Error('The event is not subscribed');
};
return service;
}
]);
While I could utilize $rootScope directly instead of implementing custom methods, enclosing $on
and $emit
from $rootScope would lead to similar drawbacks.
As such, I have the following inquiries:
- Is it advisable to include the scope reference in a service?
- What does
$$destroyed
signify? Does it indicate that AngularJS has released all internal references to the instance? - Would assigning scope as null in my service facilitate garbage collection or does AngularJS handle object deletion explicitly?
- Are there more effective strategies to achieve my objectives?