【问题标题】:Google OAuth2 + Backbone + Require.js = Problems with "this" bindingGoogle OAuth2 + Backbone + Require.js = “this”绑定问题
【发布时间】:2013-10-14 18:01:34
【问题描述】:

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

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

当它到达checkAuth 函数时,this.handleAuthResult 返回 undefined 因为checkAuthsetTimeout 内被handleClientLoad 调用。 p>

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

【问题讨论】:

  • 这个问题可能与您的问题不同。你是如何使用这个库解决身份验证和安全问题的?它是否返回一个令牌?

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


【解决方案1】:

handleClientLoad 中的 setTimeout 是问题:

window.setTimeout(this.checkAuth, 1);

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

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

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

你也可以阅读'this'发帖。

希望对您有所帮助!

【讨论】:

  • 感谢这部分帮助,但我如何处理var authorizeButton = this.$el.find('#authorize-button'); 中的this.$el更新:使用_.bindAll(this, 'handleAuthResult', 'makeApiCall');解决。
猜你喜欢
  • 2015-02-07
  • 2013-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多