Molotov
Molotov

Reputation: 35

Unwanted Multiple Calls

The code I am working on displays some messages on different pages.

page is the page number.

ActionGetMessages is an ajax request.

PushMessage just manage the content.

Here is the code:

function ShowMessages ( page ) {
    
    var oMessages = ActionGetMessages ( page );

    for ( var key in oMessages ) {
        if ( key == "end" ) continue;
        PushMessage ( oMessages [key] );
    }

    var previous_page_button = document.getElementById ( "previous_page_button");
    var next_page_button = document.getElementById ( "next_page_button" );

    if ( page > 0 ) {
        previous_page_button.style.display = "block";
        previous_page_button.addEventListener ( "click",
                                                    function () {
                                                        ShowMessages ( page - 1 );
                                                    } );
    }

    if ( !oMessages ["end"] ) {
        next_page_button.style.display = "block";
        next_page_button.addEventListener ( "click",
                                                    function () {
                                                        ShowMessages ( page + 1 );
                                                    } );
    }
}

Debugging this code I noticed that after the user have navigated back and forth the pages some times clicking (for example) the next page button cause multiple calls to ShowMessages or something like that.

Any help would be really appreciated.

Upvotes: 1

Views: 45

Answers (1)

Chris
Chris

Reputation: 7855

It's not totally clear to me what you're doing with the above code but what you describe seems to me like there are some event listeners attached multiple times that you don't want to have.

In fact when you click a button which calls ShowMessages() it will attach another event listener to the button everytime the button is clicked. So before you attach the event, try to remove the existing listener first. Have a look at:

removeEventListener

if you make sure that there are no events attached to the button before you add your event listener it should work and have the code executed just one time.

Keep in mind, that you will need to have a reference to your listener to remove it. You can do it like this:

//Define this listener globally (anywhere outside your function) 
// so you can reference it anytime or keep track of the last
// added listener somewhere. Otherwise you won't be able to
// remove it.
var myPreviousPageListener = function () {
                             ShowMessages ( page - 1 );
                         } 

previous_page_button.removeEventListener("click", myPreviousPageListener);
previous_page_button.addEventListener ( "click", myPreviousPageListener);

Upvotes: 1

Related Questions