Jump to content

Button with a callback on a specific object


Grumbler
 Share

Recommended Posts

Hey All,

 

Felt like I finally had to create an account because I got myself stuff. The short of it is this; I don't know if I am running into a JS limitation, or a phaser limitation. 

 


So, I have this object set up:

function Player(name) {                this.name = name;                this.role = "myRole";            }            Player.prototype = {                revealRole: function () {                    alert(this.role.toString());                    return this.role;                }            };

Now lets assume as some point we get a variable number of players set up with varying roles. I want to create a button for each player, and then be able to click on the button to display that player's role. I did something like this:


for (var i = 0; i < players.length; i++) {                    players[i].revealRole(); //As a test, this line works, but the next line doesn't                    var PlayerButton = game.add.button(x, y + (70 * ((i%5)+1)), 'smallbutton', revealRole, players[i], 0, 0, 1);}

This of course doesn't work for the button callback because it can't figure out the context of the revealRole method. Am I way off base here? Will this just not work?

 

Link to comment
Share on other sites

var PlayerButton = game.add.button(x, y + (70 * ((i%5)+1)), 'smallbutton', players[i].revealRole, players[i], 0, 0, 1);

You want to tell it to call the player objects revealRole function and pass it the player as a context...

This is not a limitation, but a flexability. You could attach the revealRole function to any object, and as long as the player is the context it is called on, 'this' will be the player object.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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