What I Need
Seeking an event system that meets my requirements due to the asynchronous nature of my applications. Specifically, I need the events to have the ability to fire multiple times and for listeners to immediately respond if an event has already been fired.
- The events should be able to fire multiple times (unlike promises)
- If a listener is added after an event has occurred, it should fire immediately (similar to promises)
I want to handle numerous events, such as data updates, which can occur more than once. However, I also want listeners to react right away if they've missed an event while not knowing the order in which code executes.
Proposed 'Solution'
In an AngularJS application, I came up with this solution. Though the context is AngularJS-specific, the concept applies to JavaScript in general. Below is a simplified version of the code:
app.controller('AppCtrl', function(CustomEventEmitter){
// Broadcast an event without any listener yet
CustomEventEmitter.broadcast('event');
// Add a listener for the event, fires immediately due to prior event emission
CustomEventEmitter.on('event', function(){
console.log('Event emitted');
});
// Broadcast another event
CustomEventEmitter.broadcast('event');
});
app.service('CustomEventEmitter', function(){
var
listeners = {},
memory = [];
this.broadcast = function(name){
// Emit event to all registered listeners
if(listeners[name]) {
listeners[name].forEach(function(listener){
listener();
});
}
// Store event in memory
memory.push(name);
};
this.on = function(name, listener){
// Register new listener
if(!listeners[name]) {
listeners[name] = [];
}
listeners[name].push(listener);
// Immediately call listener if event is in memory
if(memory.indexOf(name) !== -1) {
listener();
}
};
});
My Inquiries
I'm seeking answers to the following questions:
- What is considered the best practice solution for fulfilling my needs?
- Feedback on my approach to solving this issue
- Is there something obvious I am overlooking in this scenario?
I acknowledge that additional code could address some parts of this challenge, but I prefer a straightforward and concise solution.