TheLettuceMaster
TheLettuceMaster

Reputation: 15734

How to remove all jQuery events (or simply not reinitialize twice)

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? }

Upvotes: 0

Views: 79

Answers (2)

Kevin B
Kevin B

Reputation: 95022

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) {...}

Upvotes: 1

busyuqboy
busyuqboy

Reputation: 1

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.

Upvotes: 0

Related Questions