0

I ran into a scope problem when dealing with generated HTML plus event handling from within a loop.

Imagine this scenario

# var container=$('#someContainerId');

_buildField=function(index){
    return $('<div/>').data('index', index);
};

for(var i=1; i<=10; i++){
    container.append( $('<div/>').on('click', function(){
        _buildField(i);
    } );
}

In this example, _buildField() will always receive the value 10, no matter which of the div elements is being clicked.

Quite honestly, i thought it to be different, but here we go again, learning something new.

QUESTION

How can i assure the passing of the correct value (current iteration stored in i) to _buildField()?

SquareCat
  • 5,699
  • 9
  • 41
  • 75
  • This is not a duplicate for the linked question. Please ready carefully and compare the code situations. The solutions presented in the linked answer will not work in the situation explained in my question. – SquareCat Jun 27 '15 at 19:10

1 Answers1

1

ES6

If you can use ES6, opting for let instead of var may do the trick.

ES5

Since you said you need to use ES5, applying the IIFE pattern should solve your problem. Here's a contrived example:

for(var i=1; i<=10; i++) {
    (function (i) {
        setTimeout(function () {
            console.log(i);
        }, 0);
    })(i);
}

Adapting the above to your specific case should lead to:

for(var i=1; i<=10; i++) {
    (function (i) {
        container.append( $('<div/>').on('click', function(){
            _buildField(i);
        });
    })(i);
}
Ilio Catallo
  • 3,152
  • 2
  • 22
  • 40