简体   繁体   English

为什么多次触发此回调?

[英]Why is this callback fired multiple times?

I'm integrating the Google+ JS API with my website and am having a curious problem. 我正在将Google+ JS API与我的网站集成,并且遇到了一个奇怪的问题。 When my login button is pressed, I have it call the following function: 当按下登录按钮时,我将调用以下函数:

function googlePlusLogin() {
    console.log("inside googlePlusLogin()");

    gapi.auth.signIn({
        'clientid' : '[id]',
        'cookiepolicy' : 'single_host_origin',
        'scope' : 'profile email',
        'callback' : function() {console.log('test');}
    });
}

The first time I click the button, the console output is: 第一次单击该按钮时,控制台输出为:

inside googlePlusLogin()
test

As expected. 如预期的那样。 However, each additional time I click on the button (triggering the above function) the number of times test prints out increments. 但是,每增加一次单击按钮(触发上述功能), test打印输出的次数就会增加。 So, for example, the second time I click the button the output is: 因此,例如,第二次单击按钮,输出为:

inside googlePlusLogin()
test
test

The third time I click the button, the output is: 第三次单击按钮,输出为:

inside googlePlusLogin()
test
test
test

And so on.. 等等..

What is causing this behavior? 是什么导致此行为?

Note: I tagged this as JavaScript because I think this is probably a basic JS concept I just don't understand. 注意:我将其标记为JavaScript因为我认为这可能是我不了解的基本JS概念。

Quite old but I faced the same issue, so for future reference: 相当老了,但我遇到了同样的问题,因此以供将来参考:

It seems like every time you call gapi.auth.signIn , the "callback" function is added to some list of callbacks. 似乎每次您调用gapi.auth.signIn ,都会将“回调”功能添加到某些回调列表中。 Thus, set the callback parameter only the first time you call gapi.auth.signIn , ie something like 因此, 仅在首次调用gapi.auth.signIn时设置回调参数 ,即类似

function googlePlusLogin() {
  console.log("inside googlePlusLogin()");

  if(window.__callback_initialized) {
    gapi.auth.signIn({
      'clientid' : '[id]',
      'cookiepolicy' : 'single_host_origin',
      'scope' : 'profile email'
    });
  } else {
    gapi.auth.signIn({
      'clientid' : '[id]',
      'cookiepolicy' : 'single_host_origin',
      'scope' : 'profile email',
      'callback' : function() {console.log('test');}
    });
    window.__callback_initialized = true;
  }
}

modulo the DRY violation will do. 以DRY违规为模。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM