【问题标题】:How to pass parameter to callback function.如何将参数传递给回调函数。
【发布时间】:2013-02-07 15:18:53
【问题描述】:

这是我的代码。如何在回调函数中获取 for 循环的值。我需要在回调中访问 gradableGBItems[i].Title

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);
                     }


            });





        }

【问题讨论】:

    标签: asynccallback


    【解决方案1】:

    您的对象超出了匿名回调的范围。解决此问题的一种可能方法是创建一个回调函数并将其传入:

    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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2011-03-28
      • 2011-10-05
      • 1970-01-01
      相关资源
      最近更新 更多