Добавить «это» в прослушиватель событий?

1

Я создал приложение для викторины и решил переключиться с.onclick() на.addEventListener(). Чтобы заставить это работать, мне пришлось добавлять обработчики событий.

Единственный способ заставить слушателей работать, добавив следующий код в конструктор объекта Quiz..

document.getElementById('guess0').addEventListener('click', this);
document.getElementById('guess1').addEventListener('click', this);

Это работает, но я не знаю, почему. Что именно "это" делает как функция?

Целая страница кода для справки:

function Quiz(questions) {
  this.questions = questions;
  this.score = 0;
  this.currentQuestionIndex = -1;

  document.getElementById('guess0').addEventListener('click', this);
  document.getElementById('guess1').addEventListener('click', this);

  this.displayNext();
}

Quiz.prototype.displayNext = function(){
  this.currentQuestionIndex++;

  if(this.hasEnded()){
    this.displayScore();
    this.displayProgress();
  }else{
    this.displayCurrentQuestion();
    this.displayCurrentChoices();
    this.displayProgress();
  }
};

Quiz.prototype.hasEnded = function() {
 return this.currentQuestionIndex >= this.questions.length;
};

Quiz.prototype.displayScore = function() {
  let gameOverHtml = "<h1>Game is over!</h1>";
  gameOverHtml += "<h2>Your score was: " + this.score + "!</h2>";

  let quizDiv = document.getElementById('quizDiv');
  quizDiv.innerHTML = gameOverHtml;
};

Quiz.prototype.getCurrentQuestion = function() {
  return this.questions[this.currentQuestionIndex];
};

Quiz.prototype.displayCurrentQuestion = function() {
  let currentQuestion = document.getElementById('question');
  currentQuestion.textContent = this.questions[this.currentQuestionIndex].text;
};

Quiz.prototype.displayCurrentChoices = function() {
  let choices = this.getCurrentQuestion().choices;

  for (let i = 0; i < choices.length; i++) {
    let choiceHTML = document.getElementById('choice' + i);
    choiceHTML.innerHTML = choices[i];
  }
};

Quiz.prototype.handleEvent = function(event){
  if(event.type === 'click'){
    this.handleClick(event);  
  }
};

Quiz.prototype.handleClick = function(event){
  event.preventDefault();
  let choices = this.getCurrentQuestion().choices;

  if(event.target.id === "guess0"){
    this.guess(choices[0]);
  } else if(event.target.id === "guess1"){
    this.guess(choices[1]);
  }
  this.displayNext();
};

Quiz.prototype.displayProgress = function() {
  let footer = document.getElementById('quizFooter');
  if (this.hasEnded()) {
    footer.innerHTML = "You have completed the quiz!";
  } else {
    footer.innerHTML = "Question " + (this.currentQuestionIndex + 1) + " of " + this.questions.length;
  }
};

Quiz.prototype.guess = function(choice) {
  if (this.getCurrentQuestion().checkAnswer(choice)) {
    this.score++;
  }
};
Теги:

1 ответ

3
Лучший ответ

Вы делаете Quiz "классом" (как обычно мы думаем о классах, даже если JS их действительно не имеет). Когда вы выполняете quiz = new Quiz(questions), внутри конструктора Quiz this относится к вновь созданному объекту Quiz. addEventListener может принимать одно из двух значений для параметра слушателя:

Это должен быть объект, реализующий интерфейс EventListener или функцию JavaScript.

Ваша Quiz реализует необходимый интерфейс, реализуя функцию handleEvent. Таким образом, когда вы передаете вновь созданную викторину (как this) в addEventListener, вы получите quiz.handleEvent вызванный, когда произойдет событие.

  • 0
    Как он различает методы handleEvent и handleClick? Поскольку они оба получают событие в качестве параметра.
  • 0
    Это не так. Он просто хочет handleEvent , как указано, например, здесь . Ваш handleClick явно вызывается из handleEvent , но он может называться eatGrassThenMoo и принимать более листовые параметры для всех забот браузера.
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню