Search code examples
jqueryclickbindlivedie

jQuery: unbind event that was bound with live()


I have an unordered list with five list items, each with a link inside of it:

<ul>
    <li><a href="#">Link 1</a></li>
    <li><a href="#">Link 2</a></li>
    <li><a href="#">Link 3</a></li>
    <li><a href="#">Link 4</a></li>
    <li><a href="#">Link 5</a></li>
</ul>

The links have a click function bound to them with live():

$("a").live("click", function(){
    ...
});

Inside of this function is a get request that retrieves some information.

So, when any of these links are clicked, I want to prevent clicks on any of the other links from doing anything until the get is complete. I thought I could do this by unbinding the click event with die():

$("a").live("click", function(){
    $("a").not(this).die("click");
    ...
});

But this doesn't work. I don't get any errors - it just doesn't prevent the click event. What am I doing wrong?


Solution

  • The problem here is that you are trying to use live and die on a different set of elements. In order to function correctly you must apply live and die to the same selector / set of elements.

    $('a').live('click', function () { ... });
    $('a').die(); // Ok! 
    $('a').each(function () {
      $(this).die();  // Doesn't work.  
    });
    

    It sounds like you want to only temporarily disable this though until a specific operation completes. If so then you can do this with a handle / dontHandle switch.

    (function() {
      var doHandle = true;
      $('a').live('click', function() {
        if (!doHandle) {
          return;
        }
    
        // Don't handle any events until the 'get' is complete
        doHandle = false;
        doGet(this, function() { 
          // Call back for when the get is complete.  Start handling again
          doHandle = true; 
        });
    })();