Issue
I want to dynamically create event listeners in an angularjs service, however it seems that each $rootScope.$on
event listener I create in the for
loop in the service is overwritten by the following event listener. How can I dynamically create $rootScope.$on
even listeners without overwriting the previous event listener? I create events using broadcasts from my controller like $rootScope.$broadcast(EVENTS.userDeleteSuccess.event);
.
My EVENTS
constant looks like:
myApp.constant('EVENTS', {
userDeleteSuccess: {
event: 'user-delete-success',
type: 'success',
message: 'User successfully deleted'
},
...,
siteDeleteSuccess: {
event: 'site-delete-success',
type: 'success',
message: 'Site successfully deleted'
}
}
My service looks like:
myApp.service("Alert", function($rootScope, EVENTS) {
var show = function(type, message) {
$rootScope.alert = {
type: type,
message: message,
show: true
};
};
// Initialized on application startup, this is the problem method!
this.initialize = function() {
for(var event in EVENTS) {
if(!EVENTS.hasOwnProperty(event)) break;
var _event = EVENTS[event];
$rootScope.$on(_event.event, function() {
show(_event.type, _event.message);
});
}
};
return this;
});
The only event that ever gets broadcasted is always the last event in the object (siteDeleteSuccess
in this case). How can I dynamically create an event listener in a for loop that doesn't overwrite the previous $rootScope.$on
event listener?
Solution
You can do two things use an IIFE or just bind the argument(s) so they get passed into the function
IIFE
(function(event){
$rootScope.$on(event.event, function() {
show(event.type, event.message);
});
})(_event);
Binding:
$rootScope.$on(_event, function(event) {
show(event.type, event.message);
}.bind(null,_event));
Answered By - Patrick Evans
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.