2013-02-22 207 views
0

這是我的代碼。如何在回調函數中獲取for循環的值。我需要訪問回調如何將參數傳遞給回調函數。

for(var i=0; i < gradableGBItems.length ; i++) 
     { 
      //console.log(gradableGBItems[i].isGradable); 
      //console.log(gradableGBItems[i].id); 
      var resultItem=''; 

      Title=gradableGBItems[i].title; 
      //console.log(Title); 
      //console.log(gradableGBItems[i].id); 
      gradeBookbRestService.loadGradeBookItemByItemId(token, gradableGBItems[i].id, function(resultItem) { 

        //Console.log(); //Need to access value 

        if(resultItem.grade != null || resultItem.grade != undefined) 
        { 
         //console.log(resultItem.points); 
         jsonObj.push({id:resultItem.grade.id, comments:resultItem.grade.comments, isVisible:resultItem.grade.isVisible, letterGrade:resultItem.grade.letterGrade, points: resultItem.grade.points, title: Title }); 


         console.log(jsonObj); 
        } 


      }); 





     } 

回答

0

你的目標是超出範圍的匿名回調內部gradableGBItems [I] .title僞。要解決這個問題的一個可能方法是創建一個回調函數,並傳遞它:

var gradeBookItemCallback = function(gradeableItemTitle, next){ 
    return function(resultItem){ 
    //do something with gradeableItemTitle and/or resultItem. 
    next(); //call the callback. You could pass whatever you wanted to here as well. 
    } 
}); 

它會像這樣使用:

gradeBookbRestService.loadGradeBookItemByItemId(token, gradableGBItems[i].id, gradeBookItemCallback(Title, callbackFunctionHere)); 
相關問題