Could a class method be accessed from outside a nested handler method in JavaScript?

I am trying to make an XMLHttpRequest to a server using JavaScript. In the handler function, I need to call a method from the surrounding class. Is there a way to achieve this?

Understanding how this works in JavaScript can be confusing. I have experimented with different permutations of using this and bind(this), but so far, my attempts have been unsuccessful.

class ServerRequest
{
    askServer(url)
    {
        var request = new XMLHttpRequest();
        request.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                // Got the response
                this.foo().bind(this); // How do I access the foo method??
            }
        }
        request.open('GET', url);
        request.send();
    }

    foo()
    {
        // Perform some action here
    }
}

All I want is to be able to call the foo method, but when I try, Firefox Console displays the message "TypeError: this.foo is not a function".

Answer №1

There are two ways to handle this situation.

Option 1: Utilize the arrow function

askServer(url)
{
    var request = new XMLHttpRequest();
    request.onreadystatechange = () => {
        if (request.readyState == 4 && request.status == 200) {
            // Response received
            this.foo(); // How to access foo-method??
        }
    }
    request.open('GET', url);
    request.send();
}

foo()
{
    // Perform operations here
}

In this approach, the request object is referenced through a variable instead of using this, as the arrow function has a different scope binding. You can refer to the request object like this: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange#Example

Option 2: Save reference to upper scope in a variable:

askServer(url)
{
    var request = new XMLHttpRequest();
    var self = this;
    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            // Response obtained
            self.foo(); // How to access foo-method??
        }
    }
    request.open('GET', url);
    request.send();
}

foo()
{
    // Implement functionality here
}

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

Encountering an "Unmet Peer Dependency" error message while attempting to integrate bootstrap-ui into my Angular project

Currently, my goal is to successfully install angular-ui. Following the tutorials, I have attempted all commands such as: npm install angular-bootstrap However, this command results in an error message: +-- UNMET PEER DEPENDENCY angular@>=1.5 After ...

"What is the best way to ensure successful file uploads via ajax without encountering any timeouts

I am currently using ajax to upload a batch of approximately 50 files, each under 5MB. However, if the internet connection is slow, the upload process times out before even completing the first file (around 45 seconds into the upload). When attempting thi ...

What to do when encountering a problem with HTML, CSS, and JS while loading a webpage from an SD card to a WebView

I am facing an issue while loading an HTML file from the SD card to a webview. The problem is that the CSS, images, and videos are not loading properly in the webview. Compatible with Android 4.4 KitKat and Chrome version Not compatible with versions belo ...

How to automatically select the first item in a populated dropdown list using Vue JS

My HTML select element is populated with options from a server, but when using v-model, it initially selects an empty option instead of the first one. I came across a solution on a post which suggests selecting the first option manually, but since the dat ...

Creating a Dynamic Form in Google App Engine

I need guidance on how to implement a form that communicates with the server in an AJAX manner when the submit button is clicked. The goal is to display information retrieved from the server on the same page. Specifically, I am looking for assistance on ac ...

Unable to display ChartJs within the same DIV on the webpage

I'm struggling to display the Pie Chart from ChartJs in the correct DIV when I click from the left DIV. Running the chart directly works fine, but I want them both on the same page in separate DIVs. I have separate HTML files for each link and they wo ...

Material-UI - Switching thumb styles in a range slider

Looking for a way to style two entities differently on the Material-UI Slider? Entity A as a white circle and Entity B as a red circle? While using data-index can work, there's a flaw when sliding. Is there a better approach? if (data-index === 0) { ...

The scope's attribute is present, but the variable within the scope's attribute is not

Currently, I am delving into angularJS development, but encountering a perplexing issue. I am attempting to format a JSON into a table with intricate rules. The JSON structure currently is as follows: { "id":"test", "title":"Test Sample", "de ...

Encountering an issue with Server Side Rendering in React Router Dom where an error message pops up saying: "Warning: React.createElement: type is

Specific Error: A warning has occurred: React.createElement: the type provided is invalid -- it was expecting a string (for built-in components) or a class/function (for composite components), but instead received an object. in Posts in Connect(Po ...

Is there a way to compel Google Maps to load within my Angular application by implementing an Angular Directive?

I am encountering an issue where my Google Map fails to display most of the time. It seems that the map is not fully rendered when the rest of my data is populated in my Angular view. Is there a way to force the map to load? I have done some research and ...

Attempting to display the todo item in the form of <li>, however, the todo.name property is not

I am currently developing a task manager application and have encountered a puzzling issue: When I include the Todo component within the TodoList component and pass the todo item as a prop todo = {name: "ssss", status: false, id: 0.0289828650088 ...

What is the process of transferring information from one window to another window?

Is there a way to transfer data between two windows? In my parent window, I have a button that redirects to another page with a success button. When the success button is clicked on the child window, I want to display "success" text on the parent window. ...

Difficulty organizing form inputs into arrays prior to submitting them through AJAX

I am currently developing a complex multi-step form that involves various sections such as Company, Job Site, Contact, and Product. My goal is to efficiently gather the form data either as an array or object before converting it into a string for transmiss ...

Implementing custom click event for selecting checkboxes in Material-UI table rows

I have been working with the material-ui data table to implement sorting functionality. One feature I am trying to add is a checkbox on each row. The challenge I am facing is that when clicking on the checkbox, it also triggers the row link, which is not t ...

The contents of a Javascript array are not appearing within a div element

I have developed a program that reads JSON data related to a concert event. The JSON file consists of an object named global, which includes details about the band name and venue. Additionally, there is a tickets object that contains information on all ava ...

Exploring elements in Javascript

I am attempting to retrieve values from various elements when a 'a' element is clicked. Consider the following code: <tr data-id="20"> <div class="row"> <td> <div class="btn-group"> <a data-checked= ...

Setting up popover functionality in TypeScript with Bootstrap 4

Seeking assistance with initializing popovers using TypeScript. I am attempting to initialize each element with the data-toggle="popover" attribute found on the page using querySelectorAll(). Here is an example of what I have tried so far: export class P ...

JavaScript - AJAX Call Terminated after a Period on Secure Socket Layer (SSL)

Currently, my AJAX calls over an SSL connection using the Prototype JS framework run smoothly initially. However, after 10 seconds of being live on the page, they start failing with a status of 0 or 'canceled' in the Network Inspector... This is ...

What is the best way to hide a custom contextmenu in AngularJs?

I created a custom contextmenu directive using AngularJs. However, I am facing an issue where the menu is supposed to close when I click anywhere on the page except for the custom menu itself. Although I have added a click function to the document to achie ...

Issue arises when XMLHttpRequest with condition XMLHttp's status equals 200

I noticed that my Ajax script is working perfectly fine until I introduce a conditional status property. Take a look at the code below: if (XMLHttp.readyState==4 && XMLHttp.status==200){ // do something } And here's the full code snipp ...