gpt4 book ai didi

javascript - Google OAuth2 + Backbone + Require.js = "this"绑定(bind)问题

转载 作者:行者123 更新时间:2023-11-28 20:15:38 24 4
gpt4 key购买 nike

Google OAuth2 代码基于 https://developers.google.com/api-client-library/javascript/features/authentication

LoginView 有几个函数,每个函数调用另一个函数。

当到达 checkAuth 函数时,this.handleAuthResult 返回 undefined,因为调用了 checkAuthsetTimeout内通过handleClientLoad

如何处理this上下文问题?我可以对我的变量 - scopeclientIdapiKey 做同样的事情,而不是将它们设置为全局变量吗?

define(['underscore','jquery','backbone','text!templates/login.html','async!https://apis.google.com/js/client.js!onload'], function(_, $, Backbone, loginTpl) {
var LoginView = Backbone.View.extend({
template: _.template(loginTpl),

initialize: function() {
clientId = '';
apiKey = '';
scopes = 'https://www.googleapis.com/auth/plus.me';

this.handleClientLoad();
},

render: function() {
this.$el.html(this.template());
return this;
},

handleClientLoad: function() {
gapi.client.setApiKey(apiKey);
window.setTimeout(this.checkAuth, 1);
},

checkAuth: function() {
gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: true }, this.handleAuthResult);
},

handleAuthResult: function(authResult) {
var authorizeButton = this.$el.find('#authorize-button');

if (authResult && !authResult.error) {
console.log('Authorized!');
this.makeApiCall();
} else {
authorizeButton.onclick = this.handleAuthClick;
}
},

handleAuthClick: function(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, this.handleAuthResult);
return false;
},

makeApiCall: function() {
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp) {
var authorizeButton = this.$el.find('#authorize-button');
localStorage.isAuthenticated = true;
Backbone.history.navigate('', true);
});
});
}
});

return LoginView;
});

最佳答案

handleClientLoad 中的 setTimeout 是问题所在:

window.setTimeout(this.checkAuth, 1);

当 'window.setTimeout' 在 1ms 后执行并且不再在 LoginView 范围内执行时。

您可以使用'_.bind'将执行绑定(bind)到此。

window.setTimeout(_.bind(this.checkAuth, this), 1);

您还可以阅读'this'发帖。

希望这有帮助!

关于javascript - Google OAuth2 + Backbone + Require.js = "this"绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19237115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com