2011-09-21 63 views
1

我寫了一個函數來獲取列表中的項目數。它將我們要計數的項目的主鍵(list_pk)作爲輸入。然後,它查詢數據存儲對於具有「列表」等於list_pk和計數他們所有列表項...dojo.data.ItemFileReadStore.fetch()onComplete處理程序無法訪問全局變量?

function getListLength(list_pk){ 

    // Data store of list items 
    var store = getStore(); 

    dojo.global["length"] = -1; 

    // Get all list items that belong to the list 
    store.fetch({ 
     query: {list : list_pk}, 
     onComplete: function(items, request){ 
      dojo.global["length"] = items.length; 
      console.log("onComplete() length: " + dojo.global["length"]); 
     } 
    }); 

    console.log("after onComplete() length: " + dojo.global["length"]); 
} 

隨着5列表長度,上面顯示:

onComplete() length: 5 
after onComplete() length: -1 

所以它正確計數項目的數量,但它無法更新全局變量「length」。有誰知道爲什麼?

回答

3

這是正確的行爲。 store.fetch是一個異步調用。當調用onComplete時,dojo.global["length"]將被更新。如果您嘗試在store.fetch之後獲取全局變量,則onComplete可能尚未調用,因此您仍然可以獲得初始值。

只需將代碼dojo.global["length"]用於onComplete函數內。