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

Creating a basic jQuery button to switch an element's background color is a breeze

I'm new to this, so I hope this is a straightforward question. I'd like to use the bgtoggle class as a button to switch the background color of the metro class. I know I'm doing something wrong because it's not working as expected. Any ...

Cross-origin resource sharing problem (Backend developed in Express, Frontend in Angular)

I am currently utilizing Angular for my front-end development and Express for the back-end. I encountered a CORS issue with one of multiple API endpoints that have similar configurations: Failed to load http://localhost:3000/api/deletePost: No 'Acc ...

Verification of three-dimensional password format with the use of AngularJS

I am trying to implement password validation in Angular.js that requires a combination of alphabetical, numerical, one upper case letter, one special character, no spaces, and a minimum length of 8 characters. How can I achieve this using Angular.js? Here ...

Show the navigation bar only when the user is logged in using Angular 6

Utilizing JWT for authentication, I have implemented a condition to display the navigation menu for logged-in users. <app-nav *ngIf="currentUser"></app-nav> <router-outlet></router-outlet> The issue arises after logging in when th ...

Issue with Discord.js reminder command: An expected numerical value was not provided

Hey there, I'm having an issue with my reminder command as it keeps giving me a TypeError: Expected a number if(command === "remind"){ let timeuser = args[0] let reason = args.slice(1).join(" ") // !remind 10m Dream Code Uploaded ...

Office-Js Authentication for Outlook Add-ins

I am currently developing a React-powered Outlook Add-in. I kickstarted my project using the YeomanGenerator. While working on setting up authentication with the help of Office-Js-Helpers, I faced some challenges. Although I successfully created the authen ...

How can I use jQuery to add styling to my menu options?

Looking to customize my menu items: <ul> <li class="static"> <a class="static menu-item" href="/mySites/AboutUs">About Us</a> </li> <li class="static"> <a class="static-menu-item" href="/m ...

What is the best way to show a dropdown menu list using my code and JSON response object?

I am currently working on displaying a dropdown list based on the JSON response object. How can I implement it with the code snippet below? in HTML <select class="form-control" name="productCategories[]" id="productCategories< ...

I'm attempting to store the information from fs into a variable, but I'm consistently receiving undefined as the output

I'm currently attempting to save the data that is read by fs into a variable. However, the output I am receiving is undefined. const fs = require("fs"); var storage; fs.readFile("analogData.txt", "utf8", (err, data) =&g ...

Choose a specific value from a drop-down menu

Looking for a solution with this piece of code: $('#Queue_QActionID').change(function () { if ($(this).val() == '501' || $(this).val() == '502' || $(this).val() == '503' || $(this).val() == '504' || $( ...

JavaScript and .NET Core: Implementing file uploads without the use of FormData or FromFrom

Currently attempting to create a "basic" file upload feature. Utilizing JavaScript on the frontend and .NET Core on the backend. Previously, I had successfully implemented FormData / multipart, FromForm, and iFormFile. However, I have been advised agains ...

Having trouble getting your custom Angular directive to work properly with interpolation?

One of the custom Angular directives I have developed accepts a couple of inputs. Its main purpose is to highlight the matching parts of the element to which the directive is attached with the input matchTerm. This directive is intended to be used with a t ...

I'm curious if it's possible to set up both Tailwind CSS and TypeScript in Next.js during the initialization process

When using the command npx create-next-app -e with-tailwindcss my-project, it appears that only Tailwind is configured. npx create-next-app -ts If you use the above command, only TypeScript will be configured. However, running npx create-next-app -e with ...

Grunt is throwing an error message of "Cannot GET/", and unfortunately ModRewrite is not functioning properly

I've recently started using Grunt (just began last Friday). Whenever I run Grunt Serve, it displays a page with the message "cannot GET/" on it. I tried implementing the ModRewrite fix but the error persists. Any assistance would be highly appreciat ...

Creating a sliding bottom border effect with CSS when clicked

Is there a way to animate the sliding of the bottom border of a menu item when clicked on? Check out the code below: HTML - <div class="menu"> <div class="menu-item active">menu 1</div> <div class="menu-item">menu 2</ ...

Create boilerplate code easily in VS Code by using its feature that generates code automatically when creating a

Is there a way to set up VS Code so that it automatically creates Typescript/React boilerplate code when I create a new component? import * as React from "react"; export interface props {} export const MyComponent: React.FC<props> = (): J ...

Encountering a problem with the mock object in Angular 11 unit testing when converting a JSON object to a TypeScript interface

Within my Angular 11 application, I am working with a JSON response and have defined an interface to match the structure of this JSON object. The JSON object looks like this: { "division": { "uid": "f5a10d90-60d6-4937-b917- ...

Tips for incorporating images into an `.mdx` file located outside of the `public/` directory with the `next-mdx-remote` package in Next JS

I am currently developing a blog using next-mdx-remote and I am facing an issue with incorporating images in the .mdx file that are located outside of the public/ folder. If you would like to check out the complete code for my blog project, it is availabl ...

Angular now displays an unsupported Internet Explorer version message instead of showing a white screen

I am responsible for developing new features and maintaining an Angular application (version 8.3.4). Initially, we wanted the application to be compatible with all versions of Internet Explorer, but that turned out to be impractical. While the application ...

Searching for a specific data point within the latest entry of a JSON file using Javascript

I am currently in the process of utilizing a sensor to measure temperature, which is then stored in a mongo database. This data can be accessed as a JSON file by visiting ('/data'). My goal is to determine the latest entry and extract the temper ...