Sign in to follow this  
mexwell

Detect name-attribute of multiple buttons

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

 

Share this post


Link to post
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).

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.