0

我正在開發應用程序使用Facebook API。 我在想什麼很簡單 - 得到一個帖子,然後得到喜歡這個職位的人數。Facebook的API - 失去我的範圍

然後我想結合後的故事和喜歡的數量。 後來我會想要做一個循環 - 遍歷一系列的帖子。

我的問題的解釋是裏面的代碼:

$(function() { 
    $("#mybutton").click(function() { 
     FB.api("/me/posts", function (response) { 
      /* first callback 
      * 
      * i have access to global scope here. 
      */ 

      var firstpost = response.data[0]; 

      FB.api("/" + firstpost.id + "/likes", function (response) { 
       /* second callback inside the first callback 
       * 
       * here i lost my access to the first callback scope. 
       * my access is only to local and global scope. 
       * i can't see anymore what is inside firstpost variable; 
       */ 
       console.log(firstpost); 
       //this will give a reference error 
      }) 
     }) 
    }) 
}); 

也許有更好的方式來做到這一點?

回答

1

你可以只使用不同的名稱爲響應參數,但有一個更好的方法只要使用一個API調用:

/me/posts?fields=message,likes 

...或與JS SDK:

FB.api('/me/posts', {fields: 'message,likes'}, function (response) { ... } 
+0

謝謝。你能否解釋爲什麼重命名第二個「響應」最終會創建一個閉包? – LiranC

+0

最有可能是因爲它僅僅是一個參考,而不是一個副本 – luschn

+0

...但你真的應該使用一個API調用 – luschn