【问题标题】:How to pass additional arguments to callback functions in javascript when using .execute()?使用 .execute() 时如何将附加参数传递给 javascript 中的回调函数?
【发布时间】:2014-01-27 11:36:13
【问题描述】:

我正在为 Google Analytics API 使用 javascript,但我只是 JS 的新手。我有 C++ 和 Java 知识,我可以与逻辑思维相处,但有些事情让我感到困惑。在 GA API 中,我可以像这样调用函数:

gapi.client.analytics.data.ga.get({'ids':'<tableID>',
    'start-date':'<startDate>',
    'end-date':'<endDate>',
    'metrics':'<metrics>',
    'filters':'<filters>',
    'samplingLevel':'HIGHER_PRECISION',}).execute(putToVar);

putToVar() 是一个用户定义的函数,定义如下:

function putToVar(results)
{
    //do processing with the results
}

据我了解,.execute() 方法用于为异步调用gapi.client.analytics.data.ga.get() 调用回调函数。所以我假设function1().execute(function2) 所做的是以function1 的返回值作为参数调用function2?这是正确的吗?

我需要应用几个不同的过滤器并将它们存储在一个数组中以便在需要时检索,无论 API 调用是否返回结果对象(它是一个异步调用,所以我不'不知道响应什么时候来,只有回调函数可见)。

我想将存储返回对象的数组的维度传递给回调函数,以便以后可以按需检索它们,而不必担心处理响应的顺序。我这样说是因为,最初我尝试了一个 for 循环,我得到对 API 调用的响应的顺序与我为查询放置 API 调用的顺序不同,因此存在不匹配。

由于引用使用此方法调用回调函数,我想知道如何在使用.execute() 方法时将附加参数传递给这样的回调函数,当我编写putToVar() 函数时像这样:

function putToVar(results,arrayDim)
{
    //Process Results
    //Store in Array[arrayDim] the required value
}

我希望我已经说清楚了。 我已阅读以下帖子

但他们似乎都没有使用.execute() 方法,我不知道如何使用他们所说的。或者,是否以及如何修改我的 .execute() 方法(回调执行的类型)以帮助实现我的目的。

【问题讨论】:

    标签: javascript function callback google-analytics arguments


    【解决方案1】:

    添加闭包可以解决您的问题:

    for(var x = 0; x< n x ++){  //Or any other loop
       (function(x){   //Closure. This line does the magic!!
           var arrayDim = something_that_depends_on_x_or_the_loop,
               param2 = some_other_thing_that_depends_on_x;
           gapi.client.analytics.data.ga.get({'ids':'<tableID>',
             'start-date':'<startDate>',
              ...
           }).execute(function putToVar(results){   //this fn is defined inline to get access to param1, param2
               //The following alerts will use the *correct* variables thanks to the closure
               alert(x);
               alert(arrayDim);
               alert(param2);
           });
       })(x); //This one too
    }
    

    闭包很神奇。它将允许每个循环循环拥有自己的变量(不共享),因此正确的变量将在执行时位于 putToVar 内。

    我希望它很清楚,如果没有,请告诉我。

    测试一下吧!

    干杯,来自玻利维亚拉巴斯

    【讨论】:

    • 在哪里可以了解更多关于闭包的信息?谷歌只是压倒性的,问你是否可以更具体。
    • 如果你能买到“Javascript, The Good parts”这本书,它对它们有很好的解释
    • 嗯,我还没有测试它。原来是在吃早餐。很快就会做。 :)
    猜你喜欢
    • 1970-01-01
    • 2019-08-09
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 2011-10-05
    相关资源
    最近更新 更多