1

I am sure I simply didn't have enough coffee yet to see clearly, and this seems trivial, however, I have a for loop that passes some functions in a jQuery plugin. var i is passed, and of course, passes the last value of i, instead of the value it was assigned when passing through.

for (var i = 1; i < 3 + 1; i++) {
    $('#div' + i).plugin({ // i returns correctly here
    onDelete: function () {
            alert("Deleting #" + i); // i returns 4 every time - last value of i
        }
    });
}

How do I "copy" i, so it is returned as I expect? I have a workaround, but I would love to know, so I can put my head in the sand.

Michael C. Gates
  • 982
  • 1
  • 6
  • 18

1 Answers1

6

This is a well-known for loop problem. You have to wrap it in a closure each time:

for (var i = 1; i < 4; i++)(function(i) {
    $('#div' + i).plugin({
        onDelete: function() {
            alert("Deleting #" + i);
        }
    });
})(i);

Or you can use this:

for (var i = 1; i < 4; i++) {
    $('#div' + i).plugin({
        onDelete: callback(i)
    });
};

function callback(i) {
    return function() {
        alert("Deleting #" + i);
    };
}
David G
  • 94,763
  • 41
  • 167
  • 253
  • Sweet. I can't believe I didn't think of that. What does the post (i) do exactly? – Michael C. Gates Feb 19 '13 at 14:34
  • @MichaelC.Gates It's called an [immediately-invoked function expression](http://stackoverflow.com/questions/8228281/what-is-this-construct-in-javascript) (or IIFE). The `(i)` part is calling the function with the argument `i`. You should consider using my last one as it is easier to understand. – David G Feb 19 '13 at 14:35
  • I meant the very last line })(i);. Your link cleared it up for me. Thx again. – Michael C. Gates Feb 19 '13 at 14:37
  • @MichaelC.Gates Yeah that was what I was referring to. I took out the for loop brackets and replaced it with one big IIFE. – David G Feb 19 '13 at 14:38
  • @MichaelC.Gates Is there anything you still don't understand about it? I'd be happy to help. – David G Feb 19 '13 at 14:51