0

在我的index.html中我称之为Facebook SDK。在那里,我有以下代码在我的Backbone应用程序中触发控制器。Backbone/Facebook API无法按预期工作?

触发运行该调用获取登录的用户的FB.api()的功能。

骨干代码的第一个例子工作正常,但第二个有一个中间函数,我将数据传递给,但它给了我一个从facebooks all.js文件缩小的错误。

想要这中间功能的原因是可以解雇他们以不同的顺序以后。

的Facebook SDK:

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

Backbone.js的控制器代码WORKING

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

回答

0

尝试

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

或选择使用下划线的.bind()总是绑定到正确的这一点。 http://underscorejs.org/#bind

+0

感谢您的回复,这也不行。我使用下划线'_.bind()',但它也不起作用。在'all.js'中都给我一个错误 – conor909 2015-04-06 10:32:23

0

尝试使用listenTo代替App.on.类似的东西:

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