Google OAuth2 + Backbone + Require.js =“this”绑定的问题

时间:2013-10-08 00:27:18

标签: javascript backbone.js google-api oauth-2.0 requirejs

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

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

当它到达checkAuth函数时,this.handleAuthResult返回 undefined ,因为在{em> setTimeout 中调用了checkAuth 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;
});

1 个答案:

答案 0 :(得分:3)

handleClientLoad中的setTimeout是问题:

window.setTimeout(this.checkAuth, 1);

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

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

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

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

希望这有帮助!