2010-06-25 26 views
0

我們正在爲opensocial API 0.7創建小工具。 在某些功能中,我們必須決定,如果觀衆是所有者。打開社交查看器狀態(isOwner)

我們不能使用普通的功能,爲了這個目的:
return gadgets.util.getUrlParameters().viewer == gadgets.util.getUrlParameters().owner; 所以我們必須創建一個解決方法,並得到通過DataRequest的信息。

DataRequest調用回調函數並且沒有可用的返回值。 我們通過使用全局變量來設置相應的值來嘗試快速入門。

現在的問題是,該函數不會「等待」回調函數完成。我們知道這根本不是什麼好代碼/風格,但是我們試圖強制超時以進行調試。

處理回調函數中的所有代碼(如opensocial docs的示例中所述)是不可能的。 我們正在尋找類似於JavaScript中的真實'sleep()'來等待回調函數完成或另一個獲取有關查看器的所有者信息的替代方法。

globalWorkaroundIsOwner = false; 

function show_teaser(){ 
    if (current_user_is_owner()){ 
    // ... 
    } 
    // ... 
} 

function current_user_is_owner() { 

    var req = opensocial.newDataRequest(); 
    req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER), 'viewer'); 

    // This will set the the correct value 
    req.send(user_is_owner_workaround); 

    // This is an attempt to delay the return of the value. 
    // An alert() at this point delays the return as wanted. 
    window.setTimeout("empty()", 2000); 

    // This return seems to be called too early (the variable is false) 
    return globalWorkaroundIsOwner; 
} 

function user_is_owner_workaround(dataResponse) { 
    var viewer = dataResponse.get('viewer').getData(); 

    globalWorkaroundIsOwner = viewer.isOwner(); 
    // value is correct at this point 
} 

回答

1

您是否可以使用附加標誌來指示遠程查詢是否已經返回了所需的值?

var globalWorkaroundIsOwner = false; 
var workaroundStarted = false, workAroundComplete = false; 
var checker; 

function show_teaser(){ 
    if (!workaroundStarted) { 
     workaroundStarted = true; 
     current_user_is_owner(); 
    } 
    if (workaroundComplete) { 
    if (globalWorkaroundIsOwner){ 
     // ... 
    } 
    // ... 
     if (checker) { 
     clearInterval(checker); 
     } 
    } 
} 

function current_user_is_owner() { 

    var req = opensocial.newDataRequest(); 
    req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER), 'viewer'); 

    checker = setInterval("show_teaser()", 1000); 
    // This will set the the correct value 
    req.send(user_is_owner_workaround); 
} 

function user_is_owner_workaround(dataResponse) { 
    var viewer = dataResponse.get('viewer').getData(); 

    globalWorkaroundIsOwner = viewer.isOwner(); 
    workAroundComplete = true; 
    // value is correct at this point 
} 
+0

我們不能以這種方式使用它,但使用setInterval()的基本思想有助於在開始時初始化所需的值。 這樣我們只需要實現一個間隔/檢查器。 謝謝! – Smamatti 2010-06-25 11:51:17