Javascript事件监听器问题

时间:2015-03-26 00:55:40

标签: javascript event-listener

编辑2:我更改了事件监听器以调用函数来进行检查。这很好用。继承了事件监听器和新功能的变化代码:

$form.addEventListener("submit", this.addEvent.bind(this));

...

Game.prototype.addEvent = function(event) { 
    event.preventDefault();
    this.check($form[0].value);
}

我还测试了是否可以删除事件监听器,以便最终可以在gameOver函数中使用,因此测验的任何重放都不会包含重复的事件监听器。我把它放在addEventListener之后,它没有用。有什么建议?下面是removeEventListener的样子:

$form.removeEventListener("submit", this.addEvent.bind(this));

这就是我测试它的方式(不是在gameOver函数中,只是看看删除是否有效而且没有)。

$form.addEventListener("submit", this.addEvent.bind(this));
$form.removeEventListener("submit", this.addEvent.bind(this));

编辑:游戏过功能,对不起。

Game.prototype.gameOver = function() {
    update($question, "Game Over! You scored " + this.score + " points!");

    //Stop the countdown interval
    window.clearInterval(this.interval);
    hide($form);
    hide($feedback);
    show($again);

    i = 0;
    quiz = {
        "name": "Harry Potter Quiz",
        "description": "How well do you know the books/movies?",
        //"question": "What is that real name of ",
        "questions": [
            {"question": "What is Harry Potter's House?", "answer": "Gryffendor", "asked": false},
            {"question": "With What did Harry catch his first Snitch?", "answer": "Mouth", "asked": false},
            {"question": "Which potion do Harry, Ron, and Hermione take in year 2?", "answer": "Polyjuice", "asked": false}
        ]
    };
}

我正在使用Javascript制作一个小型测验游戏,并遇到了一个事件监听器的问题。

我有一个$form事件监听器来检查用户输入的答案,该答案调用check()函数。我可以玩一次游戏,但是当我想再玩一次时,由于我认为的事件监听器,事情就出错了。我尝试将$form事件监听器移动到$start$again事件监听器的位置,但是我遇到了如何访问check()方法的问题。

我有这个代码工作时,它不是面向对象但我有点卡在这里,因为我切换它。

如何让事件监听器正确地在当前代码中的位置工作,或者如果它与其他事件监听器一起移动,我该如何访问check()方法?

这应该是相关的代码。

//// DOM REFERENCES ////
//// Common convention to begin DOM variables with $ ////
var $question = document.getElementById("question");
var $score = document.getElementById("score");
var $feedback = document.getElementById("feedback");
var $start = document.getElementById("start");
var $form = document.getElementById("answer");
var $again = document.getElementById("again");
var $timer = document.getElementById("timer");

//Initializations
quiz = {
    "name": "Harry Potter Quiz",
    "description": "How well do you know the books/movies?",
    //"question": "What is that real name of ",
    "questions": [
        {"question": "What is Harry Potter's House?", "answer": "Gryffendor", "asked": false},
        {"question": "With What did Harry catch his first Snitch?", "answer": "Mouth", "asked": false},
        {"question": "Which potion do Harry, Ron, and Hermione take in year 2?", "answer": "Polyjuice", "asked": false}
    ]
};
var score = 0;
var interval = 0;
var i = 0;

//// View Functions ////
function update(element, content, klass) {
    //'element' is element to be updated
    //'content' is content to be updated with
    //A class can be added to content being added --> klass
    var p = element.firstChild || document.createElement("p");
    p.textContent = content;
    element.appendChild(p);
    if (klass) {
        p.className = klass;
    }
}

function hide(element) {
    element.style.display = "none";
}

function show(element) {
    element.style.display = "block";
}

function random(a, b, callback) {
    if (b === undefined) {
        //If only one argument is supplied, assme the lower limit is 1
        b = a;
        a = 1;
    }
    var result = Math.floor((b - a + 1) * Math.random()) + a;
    if (typeof callback === "function") {
        result = callback(result);
    }
    return result;
}

//=============================================================//

//Event Listeners
$start.addEventListener("click", function() { new Game(quiz) }, false);
$again.addEventListener("click", function() { new Game(quiz); 
                                         update($feedback, "", "clear");
                                         show($feedback) }, false);
//Hide the form at the start of the game
hide($form);
hide($again);

function Game(quiz){
    //Hide button and show form
    hide($start);
    hide($again);
    show($form);
    this.questions = quiz.questions;
    this.phrase = quiz.qustion;
    this.score = 0;
    update($score, this.score);


    //Initialize time and set up interval that counts down
    this.time = 20;
    update($timer, this.time);
    this.interval = window.setInterval(this.countDown.bind(this), 1000);

    //Add event listener to form for when it's submitted
    $form.addEventListener("submit", function(event) { 
        event.preventDefault();
        this.check($form[0].value);
    }.bind(this), false);

    this.chooseQuestion();
}

//Method Definitions
Game.prototype.chooseQuestion = function() {
    var questions = this.questions.filter(function(question){
        return question.asked === false;
    });
    //set the current question
    this.question = questions[random(questions.length) - 1];
    this.ask(this.question);
}

Game.prototype.ask = function(question){
    var quiz = this;
    alert(quiz.questions.length);
    //set the question.asked property to true so it's not asked again
    question.asked = true;
    update($question, question.question);
    $form[0].value = "";
    $form[0].focus();

    //clear previoues options
    //$form.innerHTML = "";
}

Game.prototype.check = function(answer){
    if(answer === this.question.answer){
        update($feedback, "Correct!", "right");
        //increase score by 1
        this.score++;
        update($score, this.score);
    } else {
        update($feedback, "Wrong!", "wrong");
    }
    i++;
    if(i === quiz.questions.length){
        this.gameOver();
    } else { 
        this.chooseQuestion();
    }
    //this.chooseQuestion();
}

0 个答案:

没有答案