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

Storing Byte Array in a File using JavaScript

I am working on a Java REST webservice that returns documents as byte array. I am trying to write JavaScript code that will retrieve the response from the webservice and save it to a file for downloading as a PDF. However, when testing my sample code, the ...

Utilizing a dropdown list in HTML to dynamically change images

On my HTML page, I have implemented a dropdown list box. My objective is to change an image and update a label based on the selection made from the dropdown list box. I already have an array called 'temp' which represents the number of items. The ...

Challenges with Typescript Integration in Visual Studio 2013

Currently diving into typescript as a newbie while going through the Angular tutorial using Visual Studio 2013 for work, which is also new to me. The frustrating part is that Visual Studio seems to be assuming I am going to use a different language (judgin ...

Checking for offline status in a Cordova app using Angular

I have implemented the following code to determine whether my Cordova application is online or offline. var networkState = navigator.connection.type; var states = {}; states[Connection.UNKNOWN] = 'Unknown'; states[Connection.ETHERNET] = ' ...

JavaScript function for searching YouTube videos

While browsing on stackoverflow, I came across the following code snippet: $(document).ready(function () { $("#show").click(function () { getYoutube($("#Search").val()); }); }); function getYoutube(title) { $.ajax({ type: "GET", url: yt_url ...

Convert checkbox choices to strings stored in an array within an object

I have a intricate object structure JSON{ alpha{ array1[ obj1{}, obj2{} ] } } In addition to array1, I need to include another array: array2 that will only consist of strin ...

What steps can be taken to resolve the issue of the <td> element not being allowed as a child of an <a> tag?

https://i.stack.imgur.com/nsdA7.png How can I address these warnings? I utilized the material UI table component and suspect that the warnings are originating from component={Link} to={/patient/${patient.id}} <TableContainer className={styles.tableCo ...

Utilizing JavaScript and jQuery libraries in conjunction with periods

I am a bit puzzled about when to include the period before referencing class names. For instance, in this code snippet, why is a period included before the first use of the 'active-slide' class but not for the other two instances? var primary = ...

Interactive Google Maps using Autocomplete Search Bar

How can I create a dynamic Google map based on Autocomplete Input? Here is the code that I have written: <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDeAtURNzEX26_mLTUlFXYEWW11ZdlYECM&libraries=places&language=en"></scri ...

How can we trigger a function once an ajax request has finished, without directly interacting with the ajax

I am facing a challenge where I need to trigger a JS function after an ajax call is completed, specifically when filtering posts in WordPress. The issue lies in the fact that the ajax filter tool in use is part of a WordPress plugin that cannot be modified ...

Establishing flow types and generating unchangeable records

Looking to integrate Flow with Immutable.js Records, I've set up my record like this: const MyRecord = new Immutable.Record({id: undefined}) Now when I create records using new MyRecord({id: 1}), Flow gives me an error: constructor call Construct ...

Integrating TypeScript into an established project utilizing React, Webpack, and Babel

Currently, I am in the process of integrating Typescript into my existing React, Webpack, and Babel project. I aim to include support for file extensions such as [.js, .ts, .tsx] as part of my gradual transition to Typescript. I have made some progress, b ...

Ensure that when adjusting the height of a div, the content is always pushed down without affecting the overall layout of the page

My webpage contains a div element positioned in the middle of the content, with its height being adjustable through JavaScript code. I am seeking a way to manage the scrolling behavior when the height of the div changes. Specifically, I want the content t ...

Using a JavaScript function, transmit information through an Express response

I am working on sending an application/javascript response from my Express server, utilizing data retrieved from MongoDB. This response is intended for loading content on a third party website. All components of the process have been developed, and now I ...

The message "Error: Unknown custom element: <router-view> - have you properly registered the component?" is prompting for a solution

Even though the name is correctly capitalized in all my component instances, I am still encountering an error. After researching similar issues online, it appears that the problem usually revolves around naming discrepancies. However, I have double-checked ...

What is the process of assigning a value type to a generic key type of an object in typescript?

I am currently working on developing a function that can merge and sort pre-sorted arrays into one single sorted array. This function takes an array of arrays containing objects, along with a specified key for comparison purposes. It is important to ensure ...

AngularJS array value with HTML tags is not displaying properly upon invocation

In Angular, I have an array that has the following structure: $scope.posts = [ { "ID" : id(), "Title" : "A", "Company" : "Company A", "Location" : "San Francisco, CA", "Date" : "2016-06-20", "Description ...

Ways to incorporate a scroll feature and display an iframe using JQuery

Is there a way to animate the appearance of hidden iframes one by one as the user scrolls down the website using jQuery? I have come across some solutions, but they all seem to make them appear all at once. I'm looking for a way to make the iframes s ...

How to Send Data with NodeJS by Utilizing the Finish Event

Is there a way to retrieve the JSON data sent during the nodejs finish event? This is how I send the JSON data: oResponse.json({ version: "1.0.0", author: "Someone", contributors: "also Someone" }); I would like ...

Can jQuery.jScrollPane be set to consistently display a vertical scroll bar?

Can jQuery.jScrollPane be configured to consistently display a vertical scroll bar? Is there a hidden setting or API function that can achieve this? Ideally, without needing to adjust the content pane's height or other properties. ...