The internal function does not have the correct reference. I understand why, but I do not know JS to rework it, so it works correctly

advertisements

I am creating an array of functions such as this. The url in the array is correct, but when i finally loop through this information in the arraylist.... the funt at x[1] references the last value stored into url while at the same time, x[0] is correct. Is there a way to adjust the inner url to match that of the x[0]? I was thinking to put in a param to the anon-function but i wasnt sure that was going to work. I also wasnt sure if i could work myself up the data tree, and be like function.parent[0] referencing the parent of the function and calling element 0. I guess that last idea was sort of thinking in a DOM way of logic.

var newArray = new Array();
    for(var i=0;i<fileUrls.length;++i) {
        var url = fileUrls[i];
        var x = [];//new Array();
        x = [url,
            function(){
                displayFile(url, 'image', null, ft_id, null, null, null, null, !MA.isiOS());
            },
            function(e){
                if(DEBUG) console.log('Error creating gallery thumbnail');
                alert('There was a problem creating a thumbnail');
                MA.hideMessage();
            }
        ];
        newArray.push(x);
    }
   pollingThrottler(2,newArray, function(a,b,c){
            //alert(a+"\n-----\n"+b+"\n-----\n"+c);
            //alert(bentleyPlugins.createThumbnailForPath(a,b,c));
            //alert(a);
                            //a does not reference the correct item.
            createThumbnailForPath(a,b,c);
            return;
        },function(){
            alert("success!");
        });

is the actual code.


You need a generator function for your array elements like this:

function genElement( url ) {
 return [url,
  function(){
    displayFile(url, 'image', null, ft_id, null, null, null, null, !MA.isiOS());
  },
  function(e){
    if(DEBUG) console.log('Error creating gallery thumbnail');
    alert('There was a problem creating a thumbnail');
    MA.hideMessage();
  }
 ];
}
arrayList.push( genElement( myUrl ) );

Basically what happens in your code is, that all function elements will reference the same url variable, which changes its values over the course of the loop.

When you use the generator function a copy of the url will be generated, when you call the generator function. This results in every element having its "own" url variable to reference.

EDIT

For the sake of easy to read code and performance, however, I would advise the answer of @dystroy as this is the better way to do such things in my opinion.