CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   JavaScript frameworks (http://www.codingforums.com/forumdisplay.php?f=62)
-   -   How not to add multiple listeners (http://www.codingforums.com/showthread.php?t=286890)

m2244 02-01-2013 07:44 PM

How not to add multiple listeners
 
Hello,

The code below is called when a user clicks a 'Submit' button. The problem is the line highlited below, each time they click it adds an additional listener so the event fires twicethe second time, three times the third time, etc.

What is the best way to avoid adding unwanted listeneres like this?

Code:

function checkAnswer()
{
        alert(chosenAnswer);
        if(chosenAnswer == correctAnswer)
        {               
                var xmlFeedBack = "";
                $(questionArr[questionIndex]).find('answer').each(function(){
                        if($(this).find('aText').text() == chosenAnswer)
                        {
                                xmlFeedBack = $(this).find('feedback').text();
                                alert(xmlFeedBack);
                        }
                });

                $("#feedback").html('<img src="../js_know_check/course_assets/kcbtnsprite.png" /><br/>' + xmlFeedBack + "<br/><br/>Click This Message Box to Continue.");
                questionIndex++;
                $("#feedback").click(function (evt) {alert("You clicked the message box! Great");displayQuestion()});
                numCorrect++;
        }
}


WolfShade 02-01-2013 07:46 PM

At the start of the code, set a global variable to false. Then, when the link is clicked, set it to true. Put a conditional around the highlighted line - if variable = false { code }. That way, if the variable is true, it won't fire.

Dormilich 02-02-2013 11:45 AM

I would just define the click handler outside the checkAnswer() function.

felgall 02-02-2013 10:47 PM

Another alternative would be to have the event listener remove itself again when it runs - that way it can only run once for each time it is added.


All times are GMT +1. The time now is 01:02 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.