如何在其他回调函数中包装回调函数并从那里调用?

时间:2016-03-30 22:56:21

标签: javascript callback typescript

以下是我的代码:

        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
            }
        });

当我使用这样的回调函数时。

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
                }

我没有在回调函数中获取me属性

我如何将回调函数包装在其他回调函数中,我可以在JS中获取范围

2 个答案:

答案 0 :(得分:1)

使用胖箭头:

    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 : show error in front end
            }

更多

不要使用.bindhttps://basarat.gitbooks.io/typescript/content/docs/tips/bind.html至少尚未

答案 1 :(得分:0)

使用.bind

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

function AuthResult(...) {
  // use `this` instead of `me`
}

另见How to access the correct `this` context inside a callback?