Veronica
Veronica

Reputation: 17

jquery function call isn't working

That's the code. The problem is the this.play call to start the function play() is always reporting an error. I tried a few different variations but none work.

[...]
event_listeners() {
  var result;
  $(document).on('keypress', function(evt) {
    if (evt.which == 49) {
      result = 1;
    } else if (evt.which == 50) {
      result = 2;
    } else if (evt.which == 51) {
      result = 3;
    } else if (evt.which == 52) {
      result = 4;
    } else if (evt.which == 53) {
      result = 5;
    } else if (evt.which == 54) {
      result = 6;
    } else if (evt.which == 55) {
      result = 7;
    }
    console.log(result);
    this.play(result);
  });
}

play(column) {
    console.log('play methode' + column);
    var movecount = 0;

    availableRow = this._model.checkAvailableRow(column);

    if (availableRow === -1) {
      $('.won').text("Fehler! Spalte voll!");
      return;
    }
    // Inkrementieren der Variablen, da checkAvailableRow() die Nummer der Zeile zurückgibt, hier aber der Arrayindex benötigt wird
    availableRow++;

    if (this.checkWin() == true) {
      $('.won').html((currentPlayer === "Player 1" ? "Player 1" : "Player 2") + " gewinnt!");
    }
    if (movecount === 41) {
      $('.won').html('Unentschieden!');
    }
    // Wechsel zum anderen Spieler
    this.switchTurn();
    movecount++;
  }
  [...]

When executed this error is shown in the console.

View.js:63 Uncaught TypeError: this.play is not a function

What am I doing wrong when I want to start the play() function?

Upvotes: -1

Views: 70

Answers (1)

PaulShovan
PaulShovan

Reputation: 2134

play function is outside of the scope and for this reason, it is not available inside the context of the keypress event. Using this refers the scope where the function is executed (global scope).

Using only play(result) will solve the issue.

For more information about this, you can have a look here

Upvotes: 2

Related Questions