Is there no 'this' in babylon?

Hello,

I’m trying to fill a StackPanel with simpleButtons based on what is returned from a database.
It’s working to some extent - each button has a unique name based on the appropriate data from the retrieved object. But each button has the same behavior as the final button generated. IE when I use onPointerUpObservable to console.log the button’s uniqueId, they all return the same uniqueId. Any thoughts on what I’m doing wrong?

     function makeButtons() {
        var advancedTexture = BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI(
          "UI"
        );
        var panel = new BABYLON.GUI.StackPanel();
        advancedTexture.addControl(panel);
        // console.log(topicBtnNames);
        for (let i = 0; i < topicBtnNames.length; i++) {
          var topicButton = BABYLON.GUI.Button.CreateSimpleButton(
            "but",
            topicBtnNames[i]
          );
          topicButton.width = 0.2;
          topicButton.height = "40px";
          topicButton.color = "white";
          topicButton.background = "green";
          topicButton.uniqueId = i;

          advancedTexture.addControl(topicButton);
          panel.addControl(topicButton);
          topicButton.onPointerUpObservable.add(function() {
            console.log(topicButton.uniqueId);
          });
        }
      }

The simplest way would be to reproduce this in the Playground. It would be easier to help you for live testing.

1 Like

Hey @Roibeard. I’m not sure if that ‘this’ will help you or not, because you create the buttons with the same name so…
Try something like

for (let i = 0; i < topicBtnNames.length; i++) {
      var topicButton = BABYLON.GUI.Button.CreateSimpleButton(
        "but" + i, // now all the buttons have different name
        topicBtnNames[i]
      );

Cheers!

1 Like

Hi,

This happens because you overwrite the var topicButton with each iteration, so when the listener gets called, topicButton will be the last one. You could use let topicButton instead. Alternatively, you could use the currentTarget (the this) property of the EventState:

topicButton.onPointerUpObservable.add(function(ev, state) {
            var topicButton = state.currentTarget;
            console.log(topicButton.uniqueId);
          });
4 Likes

A Woo A Hooo!!

Thanks so much this had me jammed up for days!

2 Likes

Thanks everybody!