What is the method for invoking a class method in Typescript from another method within the same class acting as an event handler?

I came across this TypeScript code that I need help with:

class MyClass {
    constructor() {
         $("#MyButton").on("click", this.MyCallback);
         this.MyMethod();        
    }

    MyCallback = () => {
        $.ajax("http://MyAjaxUrl")
        .done(function() {                
            this.MyMethod();
        });
    }

    MyMethod = () => {
        // Do some work
    }    
}

I'm encountering an issue where the JQuery ajax done function is throwing an error stating that "MyMethod is not a function". After investigating the Javascript code, I realized that the issue stems from the fact that "this" does not refer to MyClass at that point in the execution. I'm struggling to find a way to access a reference to the class in this particular scenario.

Answer №1

Is it possible to resolve this by modifying the code to:

$.ajax("http://MyAjaxUrl")
.done(() => {
    this.MyMethod();
});

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

"Exploring the world of 3rd party libraries in Angular2 with Typescript and Webpack

I've begun working on a fantastic seed project that can be found at: https://github.com/AngularClass/angular2-webpack-starter However, I've encountered an issue with integrating third-party modules. Can anyone offer guidance on how to properly a ...

Is it possible to choose several classes with identical names and then trigger a shared function simultaneously?

Is there a way to make this function target all elements with the class ".stop" and stop the video when any of these elements are clicked? window.addEventListener("load", function(event) { window.addEventListener('scroll', checkScroll, false) ...

Edit: "Submit a binary file with just JavaScript"

I am currently developing a Chrome application that utilizes the HTML5 Filesystem API to enable users to import and synchronize files. A challenge I'm facing is when attempting to sync image files, as they appear to become corrupted during the upload ...

Position the Bootstrap Modal at the start of the designated DIV

When using a Bootstrap Modal to display larger versions of thumbnails in a photo gallery, there can be some challenges. The default behavior of Bootstrap is to position the modal at the top of the viewport, which may work fine in most cases. However, if th ...

Is there a delay following the click on the file upload button?

Whenever I attempt to choose a file for upload by clicking on "Select File" (input type=file), there seems to be a lag between the moment I click the button and when the selected file appears next to the button. It almost seems as if the browser is attempt ...

Tips for managing Ajax JSON response in a PhoneGap application

Although there are a few posts on this topic, I am struggling to piece together the necessary components to make it work. I am in the process of converting a web application into an app using phonegap and I am attempting to create a search form that retri ...

The transmission of Response.StatusDescription from JsonResult to jQuery is not functioning properly

Having limited experience with MVC, Json, jQuery, etc., I am currently working on validating a form within a Modal popup using a JsonResult method to post the data to the server. Although my initial preference was to load a Partial View in the popup, that ...

Having trouble accessing BLOB images stored in a MySQL database using PHP?

I have encountered an issue while attempting to retrieve columns of the type BLOB from a MySQL database. When trying to display the data using ajax, I receive the following error message. I am unsure of what is causing this issue. I am using a jquery ajax ...

Learn how to efficiently import scripts and styles from WordPress plugins with the help of the wp_enqueue_script function

After creating my own custom Wordpress theme, everything seemed to be running smoothly. However, I soon encountered an issue where certain plugins were not functioning properly with the theme. It seems that the theme is unable to import the necessary style ...

`Erase content from a field once text is typed into a different field`

I have a Currency Converter with two input fields and a button. I enter the amount to be converted in the first field, and the result of the conversion appears in the second field. My question is: How can I automatically clear the second field when I type ...

What is the best way to delete table rows based on their assigned class?

Within my HTML document, there is the following structure: <table id="registerTable"> <tr class="leaderRegistration"> <!--table contents--> </tr> <tr class="leaderRegistration"> <!--table conten ...

Retrieve the server code periodically and automatically refresh the form elements

Let's kick things off by explaining how the application functions: (please note there are multiple users on the page such as Patient M, Patient E, and so forth) 1) Check In: Next to Patient X's name, you will find a button labeled Check In. This ...

Upgrade to Angular version 1.2.10 causes failure in $httpBackend test cases

After recently upgrading my Angular.js library from version 1.1.3 to 1.2.10, I encountered issues with my $httpBackend tests failing. The testing framework I am using is QUnit 1.12.0. Below is the setup I have in my tests: (function () { var fittingDataS ...

Tips for managing open and closed components within a React accordion and ensuring only the clicked component is opened

Unique Accordion component: const CustomAccordion = (props: AccordionProps) => { const { label, levels, activeId, id } = props const [isExpand, setIsExpand] = useState(false) const onPress = useEvent(() => { setIsExpand( ...

Instructions on enabling Angular 2 to detect dynamically added routerLink directive

As illustrated in this Plunker, I am dynamically injecting HTML into one of my elements, which can be simplified as follows: @Component({ selector: 'my-comp', template: `<span [innerHTML]="link"></span>`, }) export class MyCo ...

"Exploring the world of TypeScript Classes in combination with Webpack

If I create a TypeScript class with 10 methods and export a new instance of the class as default in one file, then import this class into another file (e.g. a React functional component) and use only one method from the class, how will it affect optimizati ...

Turn off fullPage scroll for resolution below the defined threshold

Currently, I am utilizing fullPage.js (a Javascript plugin that enables one page scrolling functionality). My objective is to disable this functionality when the window width falls below 1199. To achieve this, I have attempted calling the function on both ...

Issue with custom HTML5 video progress bar not syncing with video playback

Currently, I am working on a project using React with Typescript. I have implemented an HTML5 element range for a seek bar in the video player. The issue I am facing is that although the seek bar works correctly when manually dragged, it does not update as ...

What could be causing the tooltip to malfunction in jQuery?

The tooltip is not appearing as expected, only the title is displaying in the browser. What can be done to fix this? Below is the code snippet: HTML Code: <form action="/validate.php" method="post" id="myform"> <table width="100%" border="1"> ...

What is the best way to retrieve the canonicalized minimum and maximum values within the beforeShow method of jQuery UI's datepicker?

I have a pair of datepicker elements that I want to function as a range. When a value is set in the "low" datepicker, it should adjust the minDate and yearRange in the other datepicker, and vice versa with the "high" datepicker. The challenge I'm faci ...