How to achieve many fire events and memory events (event functions and promises combined)

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){

    // Broadcast an event. No listener added so nothing happens
    CustomEventEmitter.broadcast('event');

    // Add the event listener. Because the event allready fired, the listener gets called immediatly
    CustomEventEmitter.on('event', function(){
        console.log('Event emitted');
    });

    // Broadcast an other event
    CustomEventEmitter.broadcast('event');

});

app.service('CustomEventEmitter', function(){

    var
        listeners = {},
        memory = [];

    this.broadcast = function(name){

        // The normal broadcasting of the event to the listener
        if(listeners[name]) {
            listeners[name].forEach(function(listener){
                listener();
            });
        }

        // Push the event into the 'memory'
        memory.push(name);
    };

    this.on = function(name, listener){

        // The normal adding of the listener
        if(!listeners[name]) {
            listeners[name] = [];
        }
        listeners[name].push(listener);

        // If an event is already in memory, call the 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?

, , , , , .

, (, , , , , ), , .

+4
1

A "property" bacon.js , . (FRP). JavaScript, ,

, , .

0

Source: https://habr.com/ru/post/1531654/


All Articles