Jump to content

Detect name-attribute of multiple buttons


mexwell
 Share

Recommended Posts

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

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

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...