0

Possible Duplicate:
Javascript closure inside loops - simple practical example

I have a loop with an image.onload call like so:

for (var i = 0; i < array.length; i++){
  var item = array[i]
    , image = new Image();

  image.onload = function(){
    // do something with 'item'
  }
  image.src = url;
}

Because I do not know when the onload function is being triggered, I believe that item is getting overwritten. How do I make sure that each onload function is triggered with the item variable referencing the data that it does at the time the function is bound to the onload event?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user730569
  • 3,940
  • 9
  • 42
  • 68

2 Answers2

0

This should work.

image.onload = function(item){
    return function(){
      // do something with 'item'
    }(item);
};

What you want to do is to create "scope" so that when the event function is called, the closure brings the value you want with it.

3on
  • 6,291
  • 3
  • 26
  • 22
0

Use an IIFE to return a function that uses the current item

  image.onload = (function(param){
    return function(){
    //do something with 'param'
    }
  })(item);
Musa
  • 96,336
  • 17
  • 118
  • 137