My requirements
Due to the asynchronous architecture of my applications, I am looking for an “event” system that has the following two two properties:
- Events should be able to run several times (possibly with events, but not with promises)
- When I start listening to an event that has already been fired, I want the listener to start immediately (as with promises)
Reason 1. is that there are many events (for example, updating some data) that I want to be able to run several times. But I would like to combine this with 2. so that if the event was already fired when a listener was added, this listener is immediately called. This is because I am not always sure (and I do not want to be sure) which code fragment is run first.
My decision"
I came up with the following solution. I use this in an AngularJS application, so the context is AngularJS, but the question is applicable to Javascript in general. Please note that I have simplified the code.
app.controller('AppCtrl', function(CustomEventEmitter){
CustomEventEmitter.broadcast('event');
CustomEventEmitter.on('event', function(){
console.log('Event emitted');
});
CustomEventEmitter.broadcast('event');
});
app.service('CustomEventEmitter', function(){
var
listeners = {},
memory = [];
this.broadcast = function(name){
if(listeners[name]) {
listeners[name].forEach(function(listener){
listener();
});
}
memory.push(name);
};
this.on = function(name, listener){
if(!listeners[name]) {
listeners[name] = [];
}
listeners[name].push(listener);
if(memory.indexOf(name) !== -1) {
listener();
}
};
});
My questions
My questions are as follows:
- What is the “best practice” for my requirements?
- What do you think of my "decision"?
- Am I missing something completely obvious?
, , , , , .
, (, , , , , ), , .