espace Posted December 18, 2016 Share Posted December 18, 2016 hi, i have an array of buttons and i would assign a function that return the number of the button. my problem is when i clic on a button i receive the number 5 who is the number of buttons in my array and not the number of the concerned button itself. what i'm doing wrong ? https://jsfiddle.net/espace3d/Ldwz1w0o/ sprite = function(game,im,g,posx,posy){ this.g=g this.g=game.add.group() this.posx=posx this.posy=posy Phaser.Sprite.call(this,game,this.posx+0,this.posy,im) this.buttons=[] for (var i=0;i < 5;i++){ this.buttons[i]=game.add.button(this.posx,this.posy+i*50,im,() => this.action(i),this) this.g.add(this.buttons[i]) } this.g.add(this) } sprite.prototype = Object.create(Phaser.Sprite.prototype) sprite.prototype.constructor = sprite sprite.prototype.action=function(n){ console.log(n) } //////////////////////////////////////////////////////// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); var g1 function preload() { } function create() { var Sprite = new sprite(game,'ico',g1,0,0) } Link to comment Share on other sites More sharing options...
Tom Atom Posted December 18, 2016 Share Posted December 18, 2016 Hi, reason is, that your counter (i) stops at 5. And when any of buttons is clicked, it takes actual value of i (=5). You need to save actual value of counter somewhere, while iterating. Try this: for (var i=0;i < 5;i++){ this.buttons[i]=game.add.button(this.posx,this.posy+i*50,im,(but) => this.action(but.id),this) this.buttons[i].id = i; this.g.add(this.buttons[i]) } When button is clicked, it is passed to callback handler. In it you can read dynamicly added property "id", which saved actual value of iterator i. espace 1 Link to comment Share on other sites More sharing options...
espace Posted December 18, 2016 Author Share Posted December 18, 2016 hi, i didn't catched without your help. Thanks, another thing known. https://jsfiddle.net/modnt4uv/ Link to comment Share on other sites More sharing options...
Tom Atom Posted December 19, 2016 Share Posted December 19, 2016 Just found this article: https://medium.freecodecamp.com/lets-learn-javascript-closures-66feb44f6a44#.bvslnzzfe Example in second half is almost the same as your problem. It shows & explains other ways how to avoid your bug. Seems, most simple one is to write "let" instead of "var" for loop variable. Reason, why it works is also explained in aricle. Link to comment Share on other sites More sharing options...
Recommended Posts