What is the process of encapsulating a callback function within another callback function and invoking it from there?

Here is the code snippet I am working with:

        var me = this;
        gapi.auth.authorize({ client_id: client, scope: scope, immediate: true }, function (authResult: any) {
            if (authResult && !authResult.error) {
                me.accessToken = authResult.access_token;

            } else {

              //TODO : show error in front end
            }
        });

When I incorporate a callback function like this:

gapi.auth.authorize({ client_id: client, scope: scope, immediate: true }, AuthResult);

function AuthResult(authResult: any) {
                if (authResult && !authResult.error) {
                    me.accessToken = authResult.access_token;

                } else {

                  //TODO : show error in front end
                }

I am facing an issue where the "me" property is not accessible within that callback function.

Is there a way to encapsulate the callback function within another callback function so that I can access both "me" and "scope" in JavaScript?

Answer №1

Opt for a fat arrow function:

    gapi.auth.authorize({ client_id: client, scope: scope, immediate: true },AuthResult);

    const AuthResult = (authResult: any) => {
            if (authResult && !authResult.error) {
                this.accessToken = authResult.access_token;

            } else {
              //TODO : display error on the front end
            }

Learn More

Avoid using .bind : https://basarat.gitbooks.io/typescript/content/docs/tips/bind.html at least for now.

Answer №2

Try using the .bind method:

gapi.auth.authorize(..., AuthResult.bind(this));

function AuthResult(...) {
  // utilize `this` rather than `me`
}

For more information, check out How to access the correct `this` context inside a callback?

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

Building Background Service Workers with React Scripts and webpack Configuration

I am currently developing a chrome extension using ReactJS and TS along with a service worker. Due to the new manifest V3 requirements, I am required to specify my service worker in a specific way: "background": { "service_worker": &q ...

Error message "Encountered an unknown type 'ForOfStatement' when attempting to execute an npm library"

Currently, I am in the process of integrating the PhotoEditor SDK library into my Ruby on Rails project. To achieve this, I have been meticulously following the installation guidelines provided in the official documentation. However, during the setup proce ...

Utilizing the zIndex property on a map label does not produce any impact when combined with a GeoJSON layer

Utilizing the Google map label tool, I am trying to showcase certain property from GeoJSON data on a GeoJSON layer. However, the issue arises as the layer has a dark color and the label is appearing blurry behind the GeoJSON data layer. Despite attempting ...

What is the process for making a custom texture map to use in ThreeJS materials?

Recently, I acquired a fbx model that utilizes a UV map to efficiently texture the model. The model is composed of a single mesh that needs to be colored using 4 quadrants as shown in the image below: https://i.sstatic.net/RR6m3.png To achieve this color ...

Jquery code not responding to ajax callback

i have the following two functions defined: function populateTableData(){ jQuery('select[name="drg-select"]').change(function() { drgValue=jQuery(this).val(); url="http://localhost/ur ...

Tips for inserting HTML-tagged data into a database using AJAX and PHP

var id=$("#id").val(); var status=$("#status").val(); var jtitle=$("#jtitle").val(); function submitData(){ var id=$("#id").val(); var status=$("#status").val(); var jtitle=$("#jtitle").val(); var jdesc=tinyMCE.acti ...

Combine two elements in an array

I am faced with a challenge in binding values from an Array. My goal is to display two values in a row, then the next two values in the following row, and so on. Unfortunately, I have been unable to achieve this using *ngFor. Any assistance would be greatl ...

How to access and retrieve selected checkbox values using jQuery

<form id="myform"> <input type='checkbox' name='foo[]' value='1'> <input type='checkbox' name='foo[]' checked='true' value='2' > <input type='checkbox' ...

Transmit information via ajax and receive responses in json format

Looking to send a string and receive JSON format in return. The current method is functional but lacks the ability to return JSON code. $.ajax({ url: "getFeed.php", type: "post", data: myString }); Attempts to retrieve JSON string result in ...

Guide on creating a square within an element using JavaScript

After conducting thorough research, I find myself unsure of the best course of action. My situation involves a Kendo Grid (table) with 3 rows and 3 columns. Initially, the table displays only the first column, populated upon the page's initial load. S ...

Configuring Dialog Placement to the Top in Material-UI

I'm in the process of creating a popup dialog, but I'm encountering an issue where the dialog pops up in the center of the page. How can I position it at the very top of the page when the popup button is clicked? Below is the code snippet: < ...

How can you extract information from a text document and seamlessly incorporate it into an HTML webpage?

I am currently working with an HTML file structured like this.. <html> <body> <table border="1" cellpadding="5"> <tr> <td>Some Fixed text here</td> <td id="data">---here data as per values in external text file--- ...

problem with making ajax requests during the server-side processing of DataTables

Currently tackling server-side processing with datatables, but encountering an ajax error that I'll detail shortly. First things first, here's my code: Table <table id="call_analysis_basic_table" class="display" cellspacing="0" width="100%"& ...

Loading a chunked polyfill file in webpack only when needed - a step-by-step guide

In order to prevent unnecessary loading of polyfills, it is recommended to add some logic in the <head> section (https://webpack.js.org/guides/shimming/) <script> var modernBrowser = ( 'fetch' in window && ...

Utilize Meteor and Mongo to access a nested array object in a template with spacebars

I am trying to populate the content of a textarea by extracting data from a nested array. In my helper function, I have specified the document id and the element id. The goal is to extract the content of the text field from the findOne result and display i ...

Ways to resolve the issue of the experimental syntax 'jsx' not being enabled

I encountered an issue while trying to implement react-fancybox and received an error. To resolve the error, I executed the following commands: npm install --save-dev @babel/preset-react, npm install --save-dev @babel/plugin-syntax-jsx, and npm install -- ...

Sending a reference to the event object within a JavaScript function

There are times when we need to use the event object in JavaScript. Below is an example of how we can pass the event: function test(e){ console.log(e); e.preventDefault(); console.log("You are not going to redirect"); } HTML <a href="www. ...

Autocomplete failing to provide a valid response, returning a null value instead

Utilizing an Autocomplete feature for employee search, users can input a name and select from the list of results. However, the current onChange function logs the index value instead of the selected employee's name. Is there a way to pass the employee ...

Trigger a jQuery click event to open a new tab

On a public view of my site, there is a specific link that can only be accessed by authenticated users. When an anonymous user clicks on this link, they are prompted to log in through a popup modal. To keep track of the clicked link, I store its ID and inc ...

The javascript file is unable to detect the presence of the other file

I am facing an issue with two JavaScript files I have. The first one contains Vue code, while the other one includes a data array where I created the 'Feed' array. However, when trying to output a simple string from that array, the console throws ...