Create buttons in loop with index as parameter for event

Is there a way to set a function with the index of the creating loop as a paramater?
I’m trying it like this:

for (var i = 1; i <= 3; i++) {
    var topLeftButton = BABYLON.GUI.Button.CreateSimpleButton(i + "-Button", "Button " + i);
        panel.addControl(topLeftButton);
        topLeftButton.onPointerUpObservable.add(function () {
            myFunction(i);
        });
}

In this case the parameter in myFunction is 3 for every button.

PG example would be useful, if it is possible :slight_smile:

Variable hoisting will cause that; in your for loop, change var to ‘let’, same for ‘topLeftButton’

4 Likes

Example - https://playground.babylonjs.com/#XCPP9Y#7670

1 Like

Interesting! I’m pretty new to JS, but now I know a rule that differentiates let and var :sweat_smile:

1 Like