2011-11-16 62 views
0

可能重複:
Event handlers inside a Javascript loop - need a closure?關閉/回調在環

我一直在努力得到這個工作了一段時間,並決定只問。

我有以下幾點:

function doSomething(var1, var2) { 
    dojo.xhrGet({ 
     url:"somUrl", 
     content: {value1:var1,value2:var2}, 
     preventCache: true, 
     handleAs:"json", 
     load: function(response){ 
      for(var i in response.myObject) { 
       var listItem = new dojox.mobile.ListItem({ 
        label: response.myObject[i].name, 
        rightText: response.myObject[i].value, 
        clickable: true, 
        onClick: function() { 
         customFunction(response.myObject[i]); 
         this.transitionTo("someScreen"); 
        } 
       }); 
       myList.addChild(listItem); 
      }    
     }, 
     error:function(e){alert(e);} 
    }); 
} 
doSomething(myVal1, myVal2); 

,說customFunction(response.myObject[i]);始終返回myObject的arrray的最後一個對象行。

有人可以幫助我的語法,所以我可以使這個工作正確嗎?我一直在閱讀關於js關閉和回調的問題,但我無法完成它的工作。

感謝

+2

通過關注可能出現的重複問題,您可以節省大量時間,這些問題可能會在您試圖詢問新問題時由Stackoverflow自動顯示。許多以前的問題都涉及這個問題。 – Pointy

回答

3

你需要額外的包裝功能

onClick: (function(obj) { 
    return function() { 
     customFunction(obj); 
     this.transitionTo("someScreen"); 
    }; 
})(response.myObject[i]) 

this answer解釋:

JavaScript的作用域是功能級別的,而不是塊級別的,並且創建一個閉包就意味着封閉作用域被添加到所包含函數的詞彙環境 中。

循環結束後,函數級變量i有 值5 [注:或者,在這種情況下,最後一個屬性的response.myObject名稱],這就是內在功能「看到。

2

您需要確保i包含在封閉在每個迭代的for循環:

[...] 
    load: function(response){ 
     for(var i in response.myObject) { 
      var listItem = new dojox.mobile.ListItem({ 
       label: response.myObject[i].name, 
       rightText: response.myObject[i].value, 
       clickable: true, 
       onClick: (function(inner) { 
        return function (clickEvent) { 
         customFunction(response.myObject[inner]); 
         this.transitionTo("someScreen"); 
        } 
       }(i)) 
      }); 
      myList.addChild(listItem); 
     }    
    } 
[...] 
+0

現在如果只有JS在覈心語言中定義了更好的範圍選項。 – ChaosPandion

+0

@ChaosPandion:「JS 1.7」有'let'塊和語句 – newacct

+0

@newacct:它也在ES.next草稿中(http://wiki.ecmascript.org/doku.php?id=harmony:specification_drafts),即下ECMA版本可能會使其官方... – Christoph