将参数传递给Javascript回调函数

时间:2011-07-14 06:30:31

标签: javascript callback parameter-passing

这就是我所拥有的:

function populateElement(arg1) {

    getData(arg1); 
}

function getData(query) {

    var url = "http://foo" + query + "&callback=processData";
    // do stuff 
}

function processData(results) {

    callbackForGetData(results); 
}

function callbackForGetData(result) { 

    // process data 
}

我想再将两个参数传递给populateElement函数,如下所示:

function populateElement(arg1, arg2, arg3) {

    getData(arg1);
}

并且在callbackForGetData

中提供了arg2,arg3
function callbackForGetData(result) {

    // process data
    // use arg2, arg3 here
}

我该怎么做?

4 个答案:

答案 0 :(得分:0)

您可以将它们传递给回调并在arguments数组

中访问它们
function getData(result) {
  //result === arg1
  //arguments[0] === arg1
  //arguments[1] === arg2
  //arguments[2] === arg3
  //and so on
}

getData(arg1, arg2, arg3);

答案 1 :(得分:0)

将对象作为单个参数传递:

function populateElement(arg1, arg2, arg3) {

    var params = {"arg1":arg1,"arg2":arg2,"arg3",arg3};
    getData(params);
}

function getData(params) {

    var query = params.arg1;
    var url = "http://foo" + query + "&callback=processData";
    // do stuff 
}

答案 2 :(得分:0)

你正在寻找关闭。

function getData(query) {
    var url = "http://foo" + query + "&callback=processData";
    // do stuff
    //simulate the callback
    processData("some results");
};

function populateElement(arg1, arg2, arg3) {
    //Because we define processData here, we have a closure scope that
    // lets us see all the arguments to populateElement
    window.processData = function(results) {
        console.log("ProcessData called with results: " + results +
            ", arg2: " + arg2 + ", arg3: " + arg3);  
    };
    getData(arg1);
}
//Simulate the starting call
populateElement(4, 5, 6);

Here's a working jsfiddle.

请注意,这仅支持单个(1)待处理的getData调用。需要更复杂的方案来支持多个并发的待处理getData调用。每个都需要一个唯一的回调闭包名称,它可以像尾随的数字序列号一样简单。

答案 3 :(得分:0)

要传递更多参数,您可以使用callapply

function log(a, b, c) { console.log('A: ', a, ', b: ', b, ', c: ', c);}

log.call(window, 'first', 'second', 'third');
> A:  first , b:  second , c:  third

log.apply(window, ['first', 'second', 'third'])
> A:  first , b:  second , c:  third

但正如Peter所建议的那样,你在这里有一些异步的东西,你想把它保存在一个闭包上,而不是传递额外的参数。

有类似的东西,将数据保存在闭包中:

function processData(results) {
  // transform data
  myModule.callbackForGetData(results); 
}

window.myModule = {

  populateElement: function(arg1, arg2, arg3) {

    this.data = arguments;
    this.getData(arg1); 
  },

  getData: function(query) {

    var script = document.createElement('script');
    script.src = 'http://jsfiddle.net/echo/jsonp/?query=' + query + '&callback=processData';
    document.getElementsByTagName('head')[0].appendChild(script)
  },

  callbackForGetData: function(result) { 

      // process data 
      console.log('Args: ', this.data, ', remote result: ', result);
  }
}

// test it
myModule.populateElement(1, 2, 3)
> Args:  [1, 2, 3] , remote result:  Object {query: "1"}