0

Let's say I have this code

var callbacks = {};
for (var i in mylist){

callbacks[i] = { callback: function(){ myFunction( myList[i].someProperty ); }};

}

The code above would cause on a list like this:

myList[0].property = "zero";
myList[1].property = "one";

a result like this:

callbacks[0].callback // -> returns myFunction("one"); WRONG!
callbacks[1].callback // -> returns myFunction("one");

Is there anything I can do (in the for..in loop and without changing the fact that I access myList[i].someProperty inside of an anonymous function) to make sure that the value of myList[i].someProperty is assigned during the loop and not when the function is executed?

Saturnix
  • 10,130
  • 17
  • 64
  • 120
  • I've followed the answers in that question and I've solved the issue. Thanks for posting and sorry: I've had no idea this was a "closure" so I didn't know how to begin my search. – Saturnix Sep 13 '13 at 13:28
  • No hard feelings; I'm glad you could use that duplicate to solve your problem. You should also know that at least you're in good company: there's about [300 other questions are duplicates of that question](http://stackoverflow.com/questions/linked/750486?lq=1). – apsillers Sep 13 '13 at 13:34

1 Answers1

1

You can set a key property on your callback, and then refer to this.key:

var myList = {
    foo: {
        someProperty: 'oof'
    },
    bar: {
        someProperty: 'rab'
    }
};

var callbacks = {};
for (var i in myList) {
    callbacks[i] = { 
        key: i, //Add a key property
        callback: function(){ 
            myFunction( myList[this.key].someProperty ); 
            // And refer to    ^^^^^^^^
        }
    };
}

function myFunction(propertyValue) {
    console.log(propertyValue);
}

callbacks['foo'].callback(); //oof
callbacks['bar'].callback(); //rab
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102