Obtain the correct context within the callback

Whenever I attempt to invoke a function within a callback and utilize the class context(this), I face an issue where the callback function doesn't carry any context. The value of this ends up being undefined. I have experimented with using bind(self), but unfortunately, it did not yield the desired outcome.

export class AppComponent { 
    connect(call, callb) {
            var self = this;
            var xhttp = new XMLHttpRequest();
            xhttp.responseType = responseType;
            xhttp.open("GET", "http://localhost:3000/" + call, true);
            xhttp.onreadystatechange = function(){
                if (xhttp.readyState == 4 && xhttp.status == 200)
                {
                    callb(xhttp.response).bind(self);                
                }
            };
            xhttp.send(null);
    }


    buildXML(response){
            console.log(this) //prints undefined, should print AppComponent or something
    }

    this.connect("someCall", this.buildXML);
}

Answer №1

To ensure the correct context, employ a fat arrow function as your callback:

() => {}

Answer №2

To ensure the correct function context, you should bind it before invoking.

callb.bind(self)(xhttp.response);

Try this approach instead of:

callb(xhttp.response).bind(self);

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

How can I track monthly data in MongoDB using Mongoose?

My current project involves creating a demonstration using mongodb mongoose. The challenge I am facing is to generate collections based on the month such as SEP_2019, OCT_2019, and DEC_2019. However, it is important to note that all collection schemas are ...

How can I send data with ajax and then navigate to the page with the posted information?

I'm facing an issue where I need to send 2 Ajax requests simultaneously. The challenge is posting data to one file, receiving a response, and then posting to another page with the intention of accessing the posted values using $_post on the next page ...

Change to the parent frame using webdriver

I am facing an issue while trying to switch to the parent frame or iFrame using webdriver.js. Although I have implemented a function that works, it only goes up to the second level of frames. When attempting to switch to the parent frame from a deeper fr ...

Replace the default focus state using CSS or resetting it to a custom style

I'm looking for a solution similar to a CSS reset, but specifically for the :focus state. If such a thing doesn't exist yet, I'm interested in learning about the possible properties that can be reset or overridden in order to create a new :f ...

What is the best way to access the camera of a mobile phone through a web application?

Whenever I try to access the camera on my mobile device through a web app, I encounter an issue. While the camera works perfectly fine on the web version, it fails to show up on my mobile device unless I add https:// in the URL. How can I resolve this prob ...

IE page refresh causing jQuery blur to malfunction

Our website features a textbox with a watermark that appears and disappears based on focus and blur events in jQuery. However, we have encountered a unique issue with Internet Explorer browsers. Whenever a user clicks on the textbox, the watermark disapp ...

The requested page for angular-in-memory-web-api could not be located within the Angular 4.2.2 CLI web-api functionality

Currently, I am delving into the Angular framework (specifically version 4.2.2) and going through the Tour of Heroes tutorial. As I progressed to the HTTP section, the tutorial introduced the use of angular-in-memory-web-api to simulate a web api server. ...

The fetch() POST request is met with an error message stating "415 Unsupported Media Type"

I keep encountering a 415 error when attempting to upload a PDF file using fetch(). The PDF file resides in the same directory as the js file, and the name is correct. async function uploadFile(filePath, extension, timestamp) { const url = "https ...

Installing libraries using npm can be done in two ways: using the command `npm install`

While working, we encountered an issue where the icon for the menu block from the rc-menu library was not displaying. Every time we run mvn install We also run npm install In our package.json file, we had included this library "rc-menu":"^5.1 ...

This function in JavaScript only returns the file size of the initial FileUpload, ignoring any subsequent uploads

I have created file input boxes using a JavaScript function. If the user wants to attach more files, the function is: <script type="text/javascript"> var upload_number = 1; var attachmentlimit = 5; function addFileInput() { var d = document.cre ...

Display the selected values in a Primeng multiselect with a special character separator instead of the usual comma

I am currently utilizing primeng in conjunction with Angular 7. The default behavior of the multiselect component is to display selected values separated by commas. However, I require these values to be displayed separated by hashtags instead. & ...

Origin Access Control - Failing to Function

I've been working with a PHP API that authenticates credentials. In the beginning of my PHP script, I include these lines: header('Access-Control-Allow-Origin: http://example.org'); header('Access-Control-Max-Age: 3628800'); heade ...

Can Elements be classified as Method, Constant, or Component?

When it comes to grouping up reusable elements, I have a few options: constants, methods, or components: const someElementsConst = <div><p>Some Elements</p></div> const getSomeElements = () => <div><p>Some Elements&l ...

A square containing two triangular interactive zones

My goal is to divide a square-shaped div diagonally, creating two triangles. Each triangle should respond to the hover event. However, I have encountered a problem where if you move from one corner of the div directly to the opposite corner, the hover eve ...

How to properly import a new typings file in Typescript for Node.js applications?

I'm feeling quite overwhelmed by the different methods available for importing a Typings file. It seems like there are numerous ways to accomplish this task. Currently, I am working on a nodejs program. I successfully installed momentJS through typi ...

Guide on retrieving the interface property name or key name as a string in Typescript

Currently, I am utilizing the API of Slack and encountering situations where I send JSON requests containing strings that return as property names later on. I want to create an interface where I can send one of its property names as a string and receive t ...

AJAX successfully completes, but no response is received

I've been struggling to get the success function in my AJAX call to trigger. I know everything is set up correctly because when I make a request to my API, I can see that it's hitting the URL and the server is responding with an HTTP 200 status. ...

Encountered a JSON error while implementing in an ASP project

Currently, I am working with JavaScript and C# in aspnet. My goal is to pass 3 values from the Asp Page to the code behind, using the Json method. Below is how I achieve this: //initialize x, y and nome var requestParameter = { 'xx': x, 'yy ...

Nodejs and javascript are utilized to create dynamic SES emails

I have successfully implemented sending an email using node-ses client.sendEmail({ to: to_id, , cc: cc_id, , bcc: bcc_id, , subject: 'greetings' , message: 'your <b>message</b> goes here' , altText: 'plain text& ...

React Big Calendar encountered an error: The element type provided is not valid, as it is expected to be a string for built-in

Error One: The element type is invalid: it was expecting a string (for built-in components) or a class/function (for composite components), but received undefined. This could be due to not exporting your component correctly from the file where it's d ...