0

I am using AJAX do build a web page. It can set up a div, some buttons, and add click events. One of the buttons simply exits this "screen" and takes the user back to where they came from. Well, the user can once again rebuild this same div, and re-setup the same click events all over again.

Every time this happens, the click events registers one more time than it did previously. So it seems I am creating multiple click events by reinitialize the same code over and over again.

Here is the edited version of the code that is getting set up multiple times (if the user chooses to navigate this way).

function StartClassViewer(class_id)
{

    $.post("viewer.php", {
        _open_selected_class : 1,
        _class_id : class_id
    }, function(data)
    {
        $("#content").html(data);

        // ===================
        // Init. Exit/Menu Button
        // ===================
        $("#viewer_go_back").click(function()
        {
            InitClassViewer();
                    // THIS FUNCTION IS WHERE USER CAN BACK OUT OF PAGE
        });

        // ==================
        // Init. NEXT Button
        // ==================
        $("#viewer_next_page").click(function()
        {

                // EDITED OUT;  THIS CLICK EVENT GETS REGISTERED EACH TIME THIS FUNCTION IS RECREATED (WHEN USER COMES BACK TO THIS SECTION OF PAGE) ADDING TO PREVIOUS INITIALIZES
            });

        });

    });

Now I have tried to use the .unbind() and .off() methods in the exit function to turn off all the registered events but that doesn't seem to work. Is there a way to get around this problem? }

TheLettuceMaster
  • 15,594
  • 48
  • 153
  • 259

2 Answers2

1

If the elements those two events are bound to aren't being replaced, you don't need to rebind them every time.

$(document).ready(function(){
    $("#viewer_go_back").click(function () {
        InitClassViewer();
        ...
    });

    // ==================
    // Init. NEXT Button
    // ==================
    $("#viewer_next_page").click(function () {...});
});

function StartClassViewer(class_id) {...}
Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • But will this not work because I am setting up the handler BEFORE the actual element is created? – TheLettuceMaster May 21 '14 at 16:04
  • 2
    Apparently $.post isn't creating these two elements, otherwise you wouldn't be getting duplicate events. – Kevin B May 21 '14 at 16:04
  • You are absolutely correct. At one time it was, but I just realized when you said that that I moved it outside (and before the `post`). I'll mark this correct. – TheLettuceMaster May 21 '14 at 16:05
  • 1
    Then the concept still applies, just replace `$(document).ready(function(){...})` with whatever creates those two elements. – Kevin B May 21 '14 at 16:07
0

JQuery has the .detach method that will keep the events for DOM elements that will be added at a later time. It is used in the same way as the .remove method.