Jump to content

State variable scopes inside events


Recommended Posts



I'm taking my first steps at Phaser, creating the web version of a mobile game created in Corona SDK. I'm dealing with a little problem about variable scope inside events functions.


The game is some sort of match-3. I want to check the board layout once a piece is moved. Right now, I'm tweening 2 gems in order to swap them and trying to check matches once the animation is finished.


onMove: function(pointer, x, y, fromClick) {...var onComplete = function() {   console.log('onComplete');   console.log('gemOrigin.column: ', gemOrigin.column);   console.log('gemOrigin.row: ', gemOrigin.row);   console.log('gemTarget.column: ', gemTarget.column);   console.log('gemTarget.row: ', gemTarget.row);   var gemAux = gemOrigin;   var i1 = gemOrigin.column, j1 = gemOrigin.row;   var i2 = gemTarget.column, j2 = gemTarget.row;   gemOrigin.column = [gemTarget.column, gemTarget.column = gemOrigin.column][0];   gemOrigin.row = [gemTarget.row, gemTarget.row = gemOrigin.row][0];   console.log(i1, j1);   this.board[i1][j1].gem = this.board[i2][j2].gem;   this.board[i2][j2].gem = gemAux;      this.checkMatchs();};var originTween = this.game.add.tween(gemOrigin).to(valuesTarget, 150, Phaser.Easing.Linear.None, true); originTween.onComplete.add(onComplete); var targetTween = this.game.add.tween(gemTarget).to(valuesOrigin, 150, Phaser.Easing.Linear.None, true);},


What I want is to change gems position at the board collection (this.board[][]), but trying to access 'this.board' property inside the onComplete functions does't work (Uncaught TypeError: Cannot read property 'board' of undefined). Same goes with the this.checkMatchs() function call.


If I set a var outside the onComplete function (e.g., var board = this.board;) it works perfectly, but I don't want to do that, since there will be other 'onComplete' functions that will need to access a lot of properties or another functions of the state.


Thanks a lot for your help.

Link to comment
Share on other sites

Ok, I found the solution. I just need to pass the 'this' reference on the onComplete.add() call.

originTween.onComplete.add(onComplete, this);

But now I have another problem related with the scope of "this". How can I keep the reference within a local function declared on other function? e.g:

...evenMoreThings: function(){     console.log('give moar things!!!!');},onMove: function() {   function otherCoolThings() {      this.evenMoreThings(); // <-- Doesn't work   };   for (var i = 1; i < 10; i++){      otherCoolThings();   };},..

Is this something Phaser or just 'plain' javascript problem?

Link to comment
Share on other sites


  • Recently Browsing   0 members

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