Retrieve the attributes of a class beyond the mqtt callback limitation

Currently, I am utilizing npm-mqtt to retrieve information from a different mqtt broker.

My objective is to add the obtained data to the array property of a specific class/component every time a message is received.

However, I'm facing an issue where I don't have access to the class or its properties. Instead, it seems like I'm within the scope of the mqtt client class object.

Below you can find a snippet of the code:

this.mydata: Array<any> = [];

private fetchWithMqtt(){
    var client = mqtt.connect('ws://' + this.ip + ":" + Number(this.port) + "/mqtt");
        // set callback handlers
        client.on('close', this.onConnectionLost);
        client.on('message', this.onMessageArrived);
        client.on('connect', this.onConnect);
}

private onMessageArrived(topic, message) {
    let tempDataset = JSON.parse(message).dataset;
            this.mydata.push({ //this.mydata is undefined because this = mqtt-client
                x: tempDataset[0],
                y: tempDataset[1]
            });

My question is: How can I push data to my class property outside of this current scope?

Answer №1

When using .bind(this), you ensure that the value of this remains unchanged when your events are triggered.

Your updated code will appear as follows:

this.mydata: Array<any> = [];

private fetchWithMqtt(){
    var client = mqtt.connect('ws://' + this.ip + ":" + Number(this.port) + "/mqtt");
    // set callback handlers
    client.on('close', this.onConnectionLost.bind(this));
    client.on('message', this.onMessageArrived.bind(this));
    client.on('connect', this.onConnect.bind(this));
}

private onMessageArrived(topic, message) {
    let tempDataset = JSON.parse(message).dataset;
    this.mydata.push({
        x: tempDataset[0],
        y: tempDataset[1]
    });

However, if you need to access the client within the event handler, you can still utilize bind with a slight modification by adding mydata as an argument.

Here is the revised version of your code:

this.mydata: Array<any> = [];

private fetchWithMqtt(){
    var client = mqtt.connect('ws://' + this.ip + ":" + Number(this.port) + "/mqtt");
    // set callback handlers
    client.on('close', this.onConnectionLost.bind(client, this.mydata));
    client.on('message', this.onMessageArrived.bind(client, this.mydata));
    client.on('connect', this.onConnect.bind(client, this.mydata));
}

private onMessageArrived(mydata, topic, message) {
    let tempDataset = JSON.parse(message).dataset;
    mydata.push({ // this == client
        x: tempDataset[0],
        y: tempDataset[1]
    });

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

Steps to activate zone-conscious bluebird assurances in Angular 8

In order to make all the promises in my Angular 8 project cancelable, I embarked on a quest to find the perfect library for the job. It was during this search that I stumbled upon bluebird.js, a promising candidate ;-) Following these guidelines on integr ...

The express route parser is incorrectly detecting routes that it should not

I am encountering an issue with the following two routes: router.get('/:postId([0-9]*)', handler) router.get('/:postId([0-9]*)/like', handler) The first route is intended to only capture URLs like /posts/4352/, not /posts/3422/like. ...

Making calls to an Angular GRPC API through an Envoy proxy

Having trouble connecting to the GRPC server from the UI via Envoy. Here's the code snippet for the Envoy proxy: static_resources: listeners: - address: socket_address: address: 0.0.0.0 port_value: 8888 filter_chains: ...

Using Sinonjs fakeserver to handle numerous ajax requests

I utilize QUnit in combination with sinon. Is there a way to make sinon's fakeserver respond to multiple chained ajax calls triggered from the same method? module('demo', { beforeEach: function(){ this.server = sinon.fakeServer. ...

Issues with removing options from Autocomplete persist in React MaterialUI

Currently navigating the world of ReactJS and experimenting with Material UI's Autocomplete component. The challenge lies in managing a complex data structure where options are dynamically generated based on user selections, but removing previously se ...

Effortlessly uploading large files using axios

I am currently facing an issue and I am seeking assistance. My goal is to implement file chunk upload using axios, where each chunk is sent to the server sequentially. However, the requests are not being sent in order as expected. Below is a snippet of m ...

Live reload feature in Angular/Ionic app fails to update the app while running on Android Studio emulator

When running "ionic capacitor run android" in my Mac terminal, I can manually click the play button in Android Studio to view the application with its updated code changes. On the other hand, if I use "ionic capacitor run android -l" in my Mac terminal, t ...

Issues are arising with the for loop in an express node js app using ejs, as it is not displaying the intended data and

I am currently utilizing a for loop in JavaScript to display all the users from the database using ejs. I have included the code snippet below. This is within an express/node js application where SQL is used for data storage. <div class = "Contacts ...

Retrieving the `top` value using `$this.css("top") can either return an object or an element value

Something odd is happening with my HTML object: <div data-x="1" data-y="1" class="tile empty" style="top: 32px; left: 434px;"> <div class="inner">1:1</div> </div> When attempting to access its top property in jQuery using the ...

Unable to showcase array JSON values on HTML using ng-model

Utilizing ngTagInput for autocomplete textbox and successfully receiving suggestions. To display the values of data-ng-model (named "list") I am using: {{list}} and it is showing correctly. However, when selecting "list1", the display appears as: [{"lis ...

Utilizing type arguments in JSX components when applying withStyles

When working with React and material-ui, I am attempting to create a JSX component that can accept generic parameters while also utilizing the withStyles Higher Order Component (HOC) to inject styles. The initial approach looked something like this: cons ...

Passport - Pairing Plan "Error|The username provided for sign_request() is not recognized"

Currently experimenting with duo in node.js using passport to test its implementation in an application....Utilizing a passport-duo strategy and encountering issues when trying to apply the example provided in my own project. The GitHub repository for pass ...

Getting the percentage of code coverage in Selenium tests in relation to the web application code

I need to track the code coverage of my selenium tests in relation to the source code of the server (web application source code) that they cover. For instance, I want the tests for the login feature to measure how much of the web application's code ...

Implementing onClick functionality in RecyclerView post JSON data extraction

I recently implemented a RecyclerView in a fragment and successfully parsed JSON data from a website to display it in the RecyclerView following a helpful tutorial found at: Now, my next challenge is adding an onClick listener to the items in the Recycler ...

I am looking to show images based on the number chosen from the dropdown menu in CodeIgniter

When a number is selected from the dropdown menu, I want to display images accordingly. The options in the dropdown are 9, 12, and 18. Here is the code snippet for my view page: <form action="<?php echo base_url();?>roxcontrol/numberdisplay" id=" ...

The module "@clerk/nextjs/server" does not contain a member with the name "clerkMiddleware" available for export

Currently, I am working on Nextjs 14 with typescript and implementing authentication and authorization using Clerk. Following the instructions in the Clerk documentation, I included the code snippet below in my middleware.ts file: import { authMiddleware } ...

A plethora of unhandled DOMException errors found in a basic Vue.js application

I have been working on a Vue.js project for learning purposes, incorporating Quasar and Vuex. However, I keep encountering numerous Uncaught (in promise) DOMException errors which appear in the console. The application seems to work fine, but these red err ...

Enhance the performance of node.js when processing data from a massive file

My dilemma lies in the challenge of reading and processing a large file with numerous rows. When dealing with small files under 50kb, everything runs smoothly. However, I am faced with a 15MB file for a programming competition, which serves as a hard input ...

Validation of phone numbers based on country codes

How can I validate phone numbers based on the selected country in Angular? Are there any Angular packages specifically for this task? I've attempted to use regex, but it only works for certain countries. I need a solution that can validate mobile an ...

Guide on transmitting information from two separate pages to a PHP script simultaneously using an AJAX request

Looking to gather user information from a form and pass it onto another page smoothly. Origin Site <form action="destination.php" method="post"> Name: <input type="text" name="name"> Email: <input type="text" name="email"> <input typ ...