Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up a array of callbacks and trying to use array index as value in callback

When I setup an array of callbacks this way I get 20 in the dialog window for all callbacks. I'd like to get the index in the array instead. Is this possible? The function that calls the callback is expecting the callback to have one parameter. I don't control the caller of the callback because it is part of an external library. Any help is appreciated.

for (var i = 0; i < 20; i++) {
  callbackDB[i] = function(data) {
    alert(i);
  }
}
like image 871
Xavier Avatar asked Jan 23 '11 01:01

Xavier


People also ask

Can you return a value from a callback?

A callback function can return a value, in other words, but the code that calls the function won't pay attention to the return value.

What is array callback return?

Enforces return statements in callbacks of array's methods (array-callback-return) Array has several methods for filtering, mapping, and folding. If we forget to write return statement in a callback of those, it's probably a mistake.

Does the map () method take a callback function as an argument?

The map function takes a callback argument that uses the value, index, and collection as arguments, you can't change this. Therefore if you want to do something to each value being mapped, you should do it inside the callback function.

What is callback function explain with an example?

Note, however, that callbacks are often used to continue code execution after an asynchronous operation has completed — these are called asynchronous callbacks. A good example is the callback functions executed inside a . then() block chained onto the end of a promise after that promise fulfills or rejects.


2 Answers

Because i is evaluated when the function is called, you'll need to scope that value of i in a new function execution in order to retain the value you expect.

     // returns a function that closes around the `current_i` formal parameter.
var createFunction = function( current_i ) {
    return function( data ) {
        alert( current_i );
    };
};

     // In each iteration, call "createFunction", passing the current value of "i"
     // A function is returned that references the "i" value you passed in.
for (var i = 0; i < 20; i++) {
  callbackDB[i] = createFunction( i );
}
like image 176
user113716 Avatar answered Nov 15 '22 12:11

user113716


Another solution using an Object.

var callbackDB = new Array();

for (var i = 0; i < 20; i++) {
  callbackDB[i] = {
    value: i,
    callback: function() {
      alert(this.value);
    }
  };
}
			
callbackDB[5].callback();

In this case will be necessary to call to the function (In the example it was called "callback")

like image 39
J.S.R - Silicornio Avatar answered Nov 15 '22 11:11

J.S.R - Silicornio