Backbone/Facebook API未按预期工作

Backbone / Facebook API not working as expected?

本文关键字:工作 Facebook API Backbone      更新时间:2023-09-26

在我的index.html中,我调用了Facebook SDK。在那里,我有下面的代码触发我的主干应用程序中的控制器。

触发器运行一个函数,该函数调用获取登录用户的FB.api()

主干代码的第一个示例运行良好,但第二个示例有一个中间函数,我将数据传递给它,但它从缩小的facebooks all.js文件中返回了一个错误。

想要中间功能的原因是以后能够以不同的顺序发射它们

Facebook SDK:

FB.Event.subscribe("auth.statusChange", function (response) {
    MyApp.trigger("fb:initialize", response);
});

backbone.js控制器代码工作

    initialize: function() {
        App.on("fb:initialize", this.getUser);
    },
    getUser: function(event) {
        if (event.status === "connected") {
            FB.api("/me", function (response) {
                if (response && !response.error) {
                    console.log(response);
                }
            });
        } else {
            //do nothing
        }
    }

backbone.js控制器代码不工作

    initialize: function() {
        App.on("fb:initialize", this.testFunction);
    },
    testFunction: function(event) {
        var status = event.status;
        this.getUser(status);
    },
    getUser: function(status) {
        if (status === "connected") {
            FB.api("/me", function (response) {
                if (response && !response.error) {
                    console.log(response);
                }
            });
        } else {
            //do nothing
        }
    }

到目前为止,我已经尝试过使用我认为所谓的"闭包"。由于FB.api()是异步的,因此thiswindow相关,而不是与当前对象相关。所以我尝试在调用之外将一个变量设置为this。但它也不起作用。

例如:

        var oThis = this;
        var apiString = '/' + this.model.id + '/photos';
        FB.api(apiString, function(response){
            loadPhoto(response,  1, oThis.model);
        });

尝试

  initialize: function() {
    var _this = this;
    App.on("fb:initialize", function(event) {
      _this.getUser(event.status);
    });
  },
  getUser: function(status) {
    if (status === "connected") {
      FB.api("/me", function (response) {
        if (response && !response.error) {
          console.log(response);
        }
      });
    } else {
      //do nothing
    }
  }

或者可替换地使用下划线的CCD_ 6来始终向右绑定this。http://underscorejs.org/#bind

尝试使用listenTo而不是App.on

this.listenTo(App, 'eventName', (function(_this) {
    return function() {
        return _this.getUser();
    };
})(this));