0

I try to use dat.GUI to create multiple buttons all with same name "ShowCoord", is this possible? What I have currently is:

    for (i = 0; i < overlay.numElements; i ++)
    {
        var length = overlay.elementNumVertices[i];
        var subObj = {
            'name' : overlay.elementNames[i],
            'index' : i,
            'numVertices': overlay.elementNumVertices[i],
            "ShowCoord" : function(){
                console.log("i is " + subObj['index']);
                var verts = overlay.elementVertices[i];
                for(var j = 0; j < subObj['numVertices']; j ++)
                {
                    console.log("The coordinates are " + verts[3*j] + ", "+ verts[3*j+1] +", "+verts[3*j+2]);
                }
            }

        };
        subObjArray.push(subObj);
    }

    for(i = 0; i < subObjArray.length; i ++)
    {
        var currObj = subObjArray[i];
        var subGui = gui.addFolder(currObj['name']);
        subGui.add(currObj, 'numVertices');
        subGui.add(currObj, "ShowCoord");
    }

I now have the correct currObj['name'] and currObj['numVertices'] displayed. But all the "ShowCoord" button only contains information of the very last subObj (so console.log("i is " + subObj['index']) will print out 148 every time even if I click different button). How can I make it work? Thanks a lot!

1 Answers1

1

Try moving subGui outside the for loop and modifiy you code so that you don't reassign subGui varialbe.

var subGui = new dat.GUI();
for(i = 0; i < subObjArray.length; i ++)
{
    var currObj = subObjArray[i];
    subGui.addFolder(currObj['name']);// <--- work on this line
    subGui.add(currObj, 'numVertices');
    subGui.add(currObj, "ShowCoord");
}

Otherwise it will always be redefined with the last iterated element of for loop


Note: This is just a hint, I can't conclude more from your code.

Piotr Dajlido
  • 1,982
  • 15
  • 28
  • Thanks for answering. In the end I realized key work "this" can be used to indicate an element within an associative array. – user3799934 Mar 26 '15 at 23:19