添加"这个"到事件监听器?

时间:2017-06-21 02:07:14

标签: javascript

我正在创建一个测验应用程序并决定从.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 个答案:

答案 0 :(得分:3)

您正在制作Quiz&#34;类&#34; (正如我们通常认为的课程,即使JS没有真正拥有它们)。当您执行quiz = new Quiz(questions)时,Quiz构造函数中的this引用新创建的Quiz对象。 addEventListener可以接受侦听器参数的两个不同值之一:

  

这必须是实现EventListener接口或JavaScript函数的对象。

您的Quiz通过实施handleEvent功能来实现必需的界面。因此,当您将新创建的测验(this)传递给addEventListener时,您会在事件发生时调用quiz.handleEvent