Saturday, 18 March 2017

how to track this in a javascript 6 CLASS (not function) callback in Node.js?

I know there are lots of posts about this in javascript functions and objects, but there seems to be no similar help for javascript classes. classes are different because you cant use the "var self=this" trick to solve the problem. Solutions to not being able to get at class data include:

  1. bind. I have not been able to get this to work through the many levels of indirection required to make the program manageable. I cant find any examples of bind in callbacks without self (which doesnt work in classes) or the underscore library.
  2. arrow functions. these are fine if your entire logic is one line, but all mine are much larger and some need to be called from several places, so these are not an option I assume.
  3. var self = this. As mentioned this does not work in javacript classes.

Here is some code:

class Game{
      constructor(minPlayers) {
         this.minPlayers = minPlayers
         this.players=[]
         this.waitTimer=null
      } // constructor

      addPlayer(player) {
          this.players.plush(player)
          // if we are the first player, set a timeout waiting for others.
          if (this.players.length ==1) {
             this.waitTimer= setTimeout(this.waitForPlayers, 5000)
          } else {
             // stuff
          }
      } // addPlayer

      // this function is too long to be an arrow function.
      waitForPlayers() {
         if (this.players.length < this.minPlayers) { // error this.xx undefined.
              // do stuff
              notifyAllPlayers("Game Aborted, not enough players")  
         } // else ....
      }

      notifyAllPlayers(message){
         for (let i=0; i<this.players.length; i++) {  // error this.players undefined
            console.log(this.players[i].name) // error this.players undefined
         }
      }

} // Game

This is called by something like this:

let Game = require('./game')
let game= new Game(4)
game.addPlayer(bob)

The crux is how to get "this" from a function called by a callback called by a function? Where do all the binds go?



via John Little

No comments:

Post a Comment