Tips for accomplishing multiple event triggers and event recollection (benefits that combine features of events and promises)

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.

  1. The events should be able to fire multiple times (unlike promises)
  2. 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:

  1. What is considered the best practice solution for fulfilling my needs?
  2. Feedback on my approach to solving this issue
  3. 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.

Answer №1

If you're looking for a solution to your problem, consider using a "property" from the bacon.js library. This falls under the umbrella of functional reactive programming (FRP), with two popular JavaScript libraries that offer this functionality being:

  • bacon.js
  • Reactive Extensions

Both of these libraries provide the specific tool you need, as well as a wide range of other options.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Disable the ability to close the dialog box by clicking

this is my dialog <div *ngIf="visible" class="overlay" (click)="close()"> <div role="dialog" class="overlay-content"> <div class="modal-dialog" (click)="$event.stopPropagation()"> <!-- Modal content--> ...

What is the best method to display a service property within a controller?

If we consider the scenario where I have a controller named ctrlA with a dependency called serviceB, which in turn has a property known as propertyC. My development environment involves Angular and Typescript. When interacting with the user interface, the ...

Is it possible to transform all values in arrays to 0s in JavaScript/p5.js during the copying process?

I’m struggling with a simple code where I want to store an array of arrays containing FFT audio data. It seems like there might be a JavaScript issue because when I try to push the array into another array called spectrums, all the values inside spectr ...

Every key must be a string or number; received a function instead

I encountered a peculiar situation while working with Cucumber: Scenario Outline: Protractor and Cucumber Test InValid Given I have already...... When I fill the <number> .... Examples: | number|... | 3 |... |4 |... Moreover, I ...

Enhance your website with jQuery's animate() feature for dynamic

My current implementation of jQuery's animate function looks like this: var css1 = { display: "block", marginTop: 20 }; var direction = "marginTop"; $(element).animate(css1, 150, 'swing'); I've noticed the marginTop ...

The Cordova minification tool fails to compress files within the browser platform

I recently installed the cordova-minify plugin to compress the javascript code in my Cordova app. When I tried running the command: cordova build browser An output message appears: cordova-minify STARTING - minifying your js, css, html, and images. ...

JavaScript library unsuccessful in transferring data to PHP script

I am facing an issue while trying to transfer variables from javascript to a php file for execution. The problem is that the php file is not being called or executed, even though I have confirmed that it works properly when tested individually. $(function ...

Struggling to locate the element using xpath on a JavaScript enabled website in Selenium with Chrome

I have been attempting to extract data from a website that utilizes Javascript. Despite researching similar inquiries on xpath in Selenium, I have not found a solution. I initially tried using requests, but as the JavaScript doesn't load completely, I ...

Resizing an image with six corners using the canvas technique

Currently, I am facing two issues: The topcenter, bottomcenter, left and right anchors are not clickable. I'm struggling with the logic to adjust the image size proportionally as described below: The corner anchors should resize both height and wi ...

Within jQuery lies the power to perform multiplication operations effortlessly

I'd like to accomplish this using jQuery: var menuItems = document.getElementsByTagName("li"); for (var k = 0; k < menuItems.length; k++) { if (menuItems[k].className == "menu") { var child = menuItems[k].firstChild; if ...

Change the default values for grid column configurations in Ext JS globally

The Ext.grid.column.Column class contains the following configurations: draggable (Default: true) sortable (Default: true) menuDisabled (Default: false) Is there a way to globally change the default values of these configurations for all grid columns i ...

The Android webview encountered an error: XMLHttpRequest failed to load because the specified Origin <url> is not permitted by Access-Control-Allow-Origin restrictions

I have developed an application that loads an entire website in an Android WebView. The native code in the Android project communicates with the webpage using the Android Jockey Library, and vice versa. Everything is working smoothly except for one instan ...

Problems with radio button serialization in jQuery form plugin

I've created a basic form: <form class="dataform" method="post" id="settings" action="/"> <input type="radio" name="shareSetting" value="n"/> <input type="radio" name="shareSetting" value="y"/> <input type="button" na ...

Strategies for restricting user input within a datalist

I have a project in which I am creating a webpage that displays a list of flights that can be filtered by destination, origin, price, and more. To achieve this, I have categorized each flight within a div element using its specific properties as classes. F ...

I am experiencing an issue with applying responsiveFontSize() to the new variants in Material UI Typography

I am looking to enhance the subtitles in MUI Typography by adding new variants using Typescript, as outlined in the documentation here. I have defined these new variants in a file named global.d.ts, alongside other customizations: // global.d.ts import * a ...

Using checkboxes to select all in AngularJS

Recently, I started working with Angularjs and came across some legacy code. I am trying to figure out a way to select all checkboxes once the parent checkbox is selected. Here is the parent checkbox: <div class="form-group"> <label for="test ...

placing additional containers at the bottom rather than on the right side

Hey there! I'm currently working on a simple website and I'm having trouble getting the duplicated form rows to appear aligned below the previous one. Here's what I have right now: var i = 0; var original = document.getElementById("dupl ...

What is the best way to present JSON data retrieved from an API on different pages using Next.js?

I am currently working on two pages that are connected: one is an API page called secured.js (where user session data is processed) and the other is a normal page also named secured.js (which displays the processed content from the API page). This is the ...

Using Vuejs to implement pagination on a weekly basis

I need some help with Vue pagination. I have a ticket object, and currently, it displays in a certain way. What I'm trying to achieve is to display the tickets weekly. For example, if this week is the 31st week of the year, then from today until Sunda ...

Exploring the capabilities of multiple nested controllers in AngularJS

I am facing a challenge that I haven't been able to find a solution for online. My search form includes multiple instances of a common controller used for typeahead/autocomplete searches. Each controller is set up with different parameters for search ...