Search code examples
jqueryeventsevent-handlinglivedie

$.live() and $.die() binding and unbinding


I am having some trouble with jquery's live and die methods.

http://jsfiddle.net/fC5Nr/4/

//bind above function to clicking a
$('a').live('click', functionThatWaitsFiveSeconds)

I need to attach an event handler to clicking a link - and I want to unbind the handler while the function is running to prevent the function running over and over before it is complete (function is performing a ajax request then handling the response.

I can do all of the above just fine.

However, because the above handler is attached to a (a) tag I need to return false (to prevent the link from being followed). To do this I need to bind a different function to handle clicks and return false.

I need to know how to unbind my complicated function - while keeping my simple (return false) bound at all times.

The above fiddle should work, but after unbinding the event handler, it doesn't bind again? I've tried a few combinations of namespacing etc but cannot get this together.


Solution

  • Update got it working

       function denyRest() {
            $("body").append("<h1>return false</h1>");
            return false;
        }
        function functionThatWaitsFiveSeconds() {
            $('a').die('click.thing', functionThatWaitsFiveSeconds);
            var loader = $('<div class="loader">doing some stuff</div>');
            $('#content').append(loader);
            loader.animate({
                'width': '500'
            }, 5000, function() {
                loader.remove();
                $('a').die('click.otherthing', denyRest).live('click.thing', functionThatWaitsFiveSeconds).live('click.otherthing', denyRest);
            });
        }
    
        $('a').live('click.thing', functionThatWaitsFiveSeconds);
        $('a').live('click.otherthing', denyRest);
    

    Updated fiddle.

    I believe The issue was this.

    1. Use live to attach the handler to wait 5 seconds
    2. Use live to attach a handler that returns false to stop events.
    3. Click anchor tag, which removes the wait 5 second handler.
    4. Clicks to the anchor tag at this time will be stopped via the return false statement.
    5. NOW the return false statement is first. Once we rebind the wait 5 seconds handler it is in second place to be ran but gets denied by the return false handler.
    6. Fixed this to trash both handlers and rebind them in the correct order.