Unexpected behavior with Node js event listener

I am currently working on emitting and listening to specific events on different typescript classes. The first event is being listened to properly on the other class, but when I try to emit another event after a timeout of 10 seconds, it seems like the listener is no longer picking it up.

commonEmitter.ts

let events = require('events');
let em = new events.EventEmitter();
module.exports.commonEmitter = em;

network.ts

export class Network {

  constructor() {
    this.setConnection('connected');

    setTimeout(() => {
      commonEmitter.emit('connectionStatusChanged');
      connection = 'disconnected';
    }, 10000);
  }

private setConnection(newConnection): void {
      connection = newConnection
      commonEmitter.emit('connectionStatusChanged');
}

public isConnected(): boolean {
    return connection === 'connected';
}

}

export let connection = null;

view.ts

export class View {

private network: any;

constructor() { }


private test(){
   console.log('Online? ' + this.network.isConnected());
}

public init(){

commonEmitter.on('connectionStatusChanged', this.test());

this.network = new Network();

}

Although both events are emitted in the end, only the first one is properly "listened" to. What could be causing this issue and how can I ensure they are handled in the correct order?

Answer №1

Check out this line of code:

commonEmitter.on('connectionStatusChanged', this.test()); 

Instead of calling this.test() right away, consider changing it to the following:

commonEmitter.on('connectionStatusChanged', this.test.bind(this)); 

By doing this, you are passing a function reference that will be correctly bound to this.


Another option is to use a fat arrow callback function that preserves the lexical value of this:

commonEmitter.on('connectionStatusChanged', () => {
    this.test();
}); 

Answer №2

In order to address the second inquiry, it is necessary to pass an object as an argument when using the emit function.

// network.ts
commonEmitter.emit('connectionStatusChanged', {data: true});

Answer №3

I found success using the arrow function along with the test function call, big thanks to @jfriend000! The bind method approach didn't quite do the trick for me, but that's alright.

One more question on my mind - whenever I attempt to emit an event with arguments of any type, the listener doesn't seem to pick up on it. For instance:

// view.ts
commonEmitter.on('connectionStatusChanged', (data: boolean) => {
   console.log(data);
}); 

// network.ts
commonEmitter.emit('connectionStatusChanged', true);

If this issue is also tied to the context, how should it be handled?

Answer №4

After implementing this solution, it seems that the initial event emitted by the network class isn't being received until after a timeout when the view is refreshed. It's strange that the first event isn't being listened to initially.

// network.ts

commonEmitter.emit('connectionStatusChanged', {isOnline: true});

// view.ts

commonEmitter.on('connectionStatusChanged', (data: any) => {
      console.log('Online? ' + data.isOnline);
});

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

What steps should I follow to create an automatic image slider using Fancybox that transitions to the next slide seamlessly?

*I've recently ventured into web design and am currently experimenting with Fancybox. I'm interested in creating a slider with 3 images that automatically transitions to the next image, similar to what is seen on this website: Is it feasible to ...

Tips for efficiently delivering the create-react-app index file from your server

I have encountered a challenge in my development work with create-react-app. I am looking to serve the index.html file from the backend initially, but I am facing difficulties in achieving this goal. The main reason behind this desire is to customize the ...

Storing a date in MySQL using Vue.js and Node.js

My current tech stack consists of nodejs and express.js for the backend, vuejs for the frontend, and mysql as the database. I am facing an issue where I cannot send a date retrieved from localStorage to my mysql database. Whenever I try to send the date, ...

Leveraging Parameters in Ajax with jQuery and JavaScript

I've been exploring jQuery and trying to update a specific TD element with innerHTML. However, I'm stuck on how to capture the value of a parameter. In this scenario, my goal is to grab the user-id "1234" in order to update the TD identified as ...

How can JavaScript be utilized to disable the use of the spacebar?

I have implemented a live search feature on the website I'm working on. Currently, the search function queries the MySql database as soon as the first character is entered and updates the results with each subsequent character input. However, I'v ...

Failure occurs when attempting to send an object with an empty array using jQuery ajax

Looking to use jQuery Ajax PUT to send an object with an empty array `{value: {tags: []}}` to a Node.js express server, encountering the issue where `req.body.value` is undefined in the express `app.put()` handler. While suspecting jQuery as the culprit af ...

I'm having trouble getting rid of this stubborn loader on the website

I am currently utilizing the following template: . My objective is to eliminate the preloader progress bar that displays the loading progress of the page in percentage. The files associated with this preloader are as follows: Loader CSS File - www[dot]the ...

Most effective method for showcasing the image once it has been successfully loaded

At the moment, I am considering two methods to display an image after it has been loaded. Initial Method <img id="myImage" /> var img = new Image(), x = document.getElementById("myImage"); img.onload = function() { x.src = img.src; }; img ...

Next.js does not support Video.js functionality when using server side rendering

I'm struggling to set up video.js in my next.js project and encountering issues. When the player is loading, it initially appears black and then disappears abruptly. A warning message in the console reads: "video.es.js?31bb:228 VIDEOJS: WARN: T ...

Working with Angular2: Linking dropdown values with any number of items

Is there a way to dynamically bind drop down values with numbers from 1 to 100 using a loop in Angular2? I am currently using Ngprime dropdown for a limited number of values, but how can I achieve this for any number of values? Here is the template: < ...

Incorporating JS objects into HTML: A comprehensive guide

Here is a snippet of code from my JavaScript file: var formStr = "<h5>How many books?:</h5><input type='number' id='bookinput' value='' /><input type='button' value='submit' onclick=& ...

Ensure that the Popover vanishes upon scrolling the page - Material UI (MUI) v5 compatibility with React

When implementing the MUI v5 standard pattern for displaying a popover upon hovering over another element, everything works smoothly except for one scenario: If you hover over the element And without moving the mouse, use the scroll wheel to scroll throug ...

How to utilize a parameter value as the name of an array in Jquery

I am encountering an issue with the following lines of code: $(document).ready(function () { getJsonDataToSelect("ajax/json/assi.hotel.json", '#assi_hotel', 'hotelName'); }); function getJsonDataToSelect(url, id, key){ ...

What is causing the digest loop from this angular filter grouping?

My goal is to showcase a variety of items in batches of N at a time. The reason for chunking the items is because I need them to be laid out in a tabular or gridded format (each group of N items forms a row, with each item being a column). Below is my atte ...

Creating an Escape key press event in plain Typescript without using JQuery

Is there a way to trigger an Escape button press event in Angular unit tests? const event = document.createEvent('UIEvent'); event.initUIEvent('keydown', true, true, window, 0); (<any>event).keyCode = 27; (<any ...

What is the procedure for altering a particular element using ajax technology?

I have an AJAX request that updates the user information. I need to retrieve a specific value from the response and update the content of a specific element. For example, here is the element that needs to be changed: <div id="changeMe"><!-- New ...

Is $timeout considered a questionable hack in Angular.js development practices?

Here's a question for you: I recently encountered a situation where I needed to edit the DOM on a Leaflet Map in order to manipulate the appearance of the legend. To workaround an issue where the map wasn't generating fast enough to access the n ...

Troubleshooting Problem with Uploading Several Photos to Firebase Storage

I need assistance with uploading multiple photos to Firebase Storage. Despite my efforts, it seems that the original upload keeps getting overwritten and the folder with the venueID property is not being created. Can someone provide some guidance on this i ...

Leverage the power of express-session in your NextJS project

Currently, I am working on developing a login system using NextJS and MySQL. I am looking to implement sessions for user login, but I am unsure of how to integrate express-session with NextJS. Can anyone provide guidance on whether express-session can be ...

Obtaining JSON information within the AngularJS Scope

I am delving into the world of AngularJS for the first time and trying to understand it by following this example: http://jsfiddle.net/SAWsA/11/ After successfully acquiring data in JSON format, I encountered no issues. Here is a snippet of the JSON data: ...