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

Modifying controller variable using a service

When working with the "ok" function of a modal, I encountered an issue while trying to update a variable from the scope that opened the modal. $scope.modalOptions.assets.length = 0; The above code successfully updates the variable "assets" in the parent ...

Manipulating an element in the JSON data is causing alterations to the preceding elements

I am facing a challenge with two JSON arrays. $scope.arr1 = [ { "id": 1, "first_name": "Philip", "last_name": "Kim", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e6e7577732e5e737b7a777f78776c7b307d717 ...

What is the best way to link HTML transformations across several classes?

Is it possible to combine multiple transforms in a single element to create a unique end result? It seems that when applying multiple transform properties to an element, only one of them will be recognized. For example, trying to transform a div with bot ...

Retrieving data from Node.js within an Angular application

I am currently working on retrieving data from MongoDB and displaying it on my website. However, I am facing an issue in sending the entire fetched object to a specific port (the response) so that I can retrieve it from Angular. I also need to know how to ...

Using both CASE and MATCH operators within an array in Neo4j's Cypher Query Language (

Using the code snippet below, I am attempting to retrieve all details related to user data where the checked value is either 1 or 0. I have noticed that 'WHERE flight.checked IN check' does not seem to be properly working. Is it appropriate to u ...

JavaScript drop-down menu malfunctioning

I am currently in the process of learning web development languages, and I'm attempting to create a dropdown list using JavaScript (I previously tried in CSS without success). I would greatly appreciate it if you could review my code and let me know ...

A step-by-step guide on initializing and setting a cookie value with expiration

Below is the code I have added. Can someone please help me locate the bug? Here is the code snippet: $_SESSION['browser'] = session_id(); setcookie($expire, $_SESSION['browser'], time() + (60 * 1000), "/"); echo "Value is: " . $_COO ...

What are the steps to create an AngularJS application with AWS integration?

Should I deploy an EC2 instance and set up a web server like Node.js on it, or is it necessary to use the AWS SDK for JavaScript? (Please note that this project involves interacting with an application server, not just a static AngularJS app) ...

In Node.js, the module.exports function does not return anything

After creating a custom function called module.exports, const mongoose = require("mongoose"); const Loan = require("../models/loan_model"); function unpaidList() { Loan.aggregate([ { $group: { _id: "$ePaidunpaid", data: { $pus ...

Retrieving a specific time using a JavaScript interface

I am currently implementing a JavaScript control that can be found on this website: My question is, how can I retrieve the selected date from the control in order to pass it to a postback page? I attempted to figure it out myself, but my JavaScript skills ...

Leveraging the power of Map and Sort to display the items containing image URLs alongside their respective timestamps

I'm diving into firebase and utilizing react, and currently I've come across this snippet of code: {photos.map(url => ( <div key={url} style={card}> <img src={url} style={image} /> <div s ...

Generate HTML tags dynamically within a JSON document using PHP

Is there a way to incorporate HTML markups (generated dynamically by a CMS) into a JSON file? I am aware that in the html string, one must escape double quotes by adding "" as shown below. { "title": "Title", "da ...

Excessive use of the style attribute within an AngularJS directive

My AngularJS directive includes the replace: true and template: <span style="color: red;"></span> properties. However, when I use this directive in my code, it appears that the style attribute is duplicated in the rendered HTML: <span style= ...

Error in MUI: Unable to access undefined properties (reading 'drawer')

Recently, I encountered an unexpected error in my project using MUI v5.0.2. Everything was working fine just a week ago with no errors, but now I'm facing this issue without any changes made to the code: Error: TypeError: Cannot read properties of un ...

Restore checkbox to default setting

Is it possible to reset checkboxes in a form back to their initial status using javascript, PHP, jQuery, or any other method? Here is the code I am currently using: <form method="POST> <input type="text" name="name" id="name" value="default val ...

Issues with login validation in HTML when utilizing JSON and PHP

While creating a login form in HTML using JSON and PHP, I encountered an issue where the if statements in the success function were not working properly. However, the beforeSend and error functions are functioning as expected. Can someone assist me in iden ...

Tips for retrieving a child component's content children in Angular 2

Having an issue with Angular 2. The Main component displays the menu, and it has a child component called Tabs. This Tabs component dynamically adds Tab components when menu items are clicked in the Main component. Using @ContentChildren in the Tabs comp ...

Socket.io: sending signals without receiving any responses

I've been working on a real-time socket.io project that involves a collaborative whiteboard app. I'm facing some issues with emitting data. server.js const express = require('express') const app = express(); const http = require(&apos ...

Implementing Do Not Track in an express application

I am trying to implement a feature named "consent" in my Nodejs express app that utilizes the Do Not Track (DNT) functionality from browsers. This function is supposed to integrate Google analytics on rendered pages only when DNT is not active or its state ...

Tips for updating the content within an HTML tag with jQuery

I am looking to update the parameter value of an applet tag based on the selection from a dropdown menu. As I am new to jQuery, I would appreciate any guidance on how to achieve this using jQuery. This is my current applet code: <applet id="decisiontr ...