mexwell Posted July 19, 2014 Share Posted July 19, 2014 Hey out there, I created some buttons like this:generateButtons() { for (var i = 0, j = 0; i < 3; i++, j++) { console.log(i); //shows 0,1,2 //create upgrade button this.upgradeButton = this.game.add.button(610, 225 + (j * 165), 'skillButton', function helper() { this.dosth(this.upgradeButton.name); }, this, 2, 1, 0); upgradeButton.name = 'button' + i; }}dosth(buttonname) { console.log('show me the clicked buttonname: ' + button name); //always 'button2'}And now i want to detect the exact name-attribute of the pressed button in the "dosth"-function. But i always get the name of the latest number of the "i" - in this case its: "button2". I know i can create three separate buttons but i would like to do it in a dynamic way. Can anyone give me some advice?Thanks Link to comment Share on other sites More sharing options...
mexwell Posted July 20, 2014 Author Share Posted July 20, 2014 I used a global variable to generate all the buttons. But by using a local variable all works fine. Link to comment Share on other sites More sharing options...
lewster32 Posted July 20, 2014 Share Posted July 20, 2014 function generateButtons() { // use a reusable local var just to store a reference so we can set each button's name var button; for (var i = 0, j = 0; i < 3; i++, j++) { // pass the 'dosth' function directly as the callback button = this.game.add.button(610, 225 + (j * 165), 'skillButton', dosth, this, 2, 1, 0); // set the name of this button button.name = 'button' + i; }}function dosth(button) { // the first parameter of the callback is the button instance that was pressed, so use that to get the name console.log('show me the clicked buttonname: ' + button.name);}Scope strikes again! This is the correct way to do what you're trying to do. You can see it working here: http://jsfiddle.net/lewster32/2U97k/ Just for completeness, the callback returns 3 parameters - the Button being pressed, the Pointer that triggered it and a boolean indicating whether the pointer is over it or not (obviously will be true for a button). Link to comment Share on other sites More sharing options...
mexwell Posted July 20, 2014 Author Share Posted July 20, 2014 Thanks lewster for the details! lewster32 1 Link to comment Share on other sites More sharing options...
Recommended Posts