How to replace event handler with jQuery?

I have a site that uses AJAX for navigation. I have two pages in which I use the click and drag function with

$(".myDragArea").mousedown(function(){
  do stuff...
  mouseDrag = true; // mouseDrag is global.
});

$("body").mousemove(function(){
  if (mouseDrag) {
    do stuff...
  }
});

$("body").mouseup(function(){
  if (mouseDrag) {
    do stuff...
    mouseDrag = false;
  }
});

I'm just typing this, so I apologize for random syntax errors. Two parts of the site use an almost identical code, with the only difference being inside the function $("body").mouseup(). However, if I get access to the first part, then go to the second part, the code that works in mouseup does not change. I went through the code using firebug and no errors or throws at startup $("body").mouseup()when loading the second part.

So why doesn't the event handler change when I run the $("body").mouseup()second time?

+3
3

$("body").mouseup(function) .
, $("body").unbind('mouseup');.

+3

$("body").mouseup( ... ) , .

, , .

4 .unbind(). :

  • Nuclear option - body

    $("body").unbind();
    

    . .

  • The elephant gun - mouseup body

    $("body").unbind('mouseup');
    

    , .

  • The surgeon scalpel - body

    $("body").unbind('mouseup', myMouseUpV1);    
    

    , . :

    myMouseUpV1 = function(){
      if (mouseDrag) {
        do stuff...
        mouseDrag = false;
      }
    }
    
    $("body").mouseup(myMouseUpV1);
    
    $("body").unbind('mouseup', myMouseUpV1);
    $("body").mouseup(myMouseUpV2); // where you've defined V2 somewhere
    
  • Scalpel with anesthesia (, ) - , . . .bind() , (, .mouseover()).
    :

    $("body").bind('mouseup.mySpace', function() { ... });
    

    $("body").bind('mouseup.mySpace', myHandler);
    

    , , :

    $("body").unbind('mouseup.mySpace');
    

    , :

    $("body").unbind('mouseup.mySpace1.mySpace2.yourSpace');
    

    , !

    $("body").unbind('.mySpace')
    

    . $("body").unbind(myHandler) , ($("body").unbind('mouseup', myHandler))!


PS: .unbind(event). , .

var timesClicked = 0;
$('input').bind('click', function(event) {
  alert('Moar Cheezburgerz!');
  timesClicked++;
  if (timesClicked >= 2) {
    $('input').unbind(event);
    $('input').val("NO MOAR!");
  }
});​
+10

jquery "" .

Ajax DOM (.. ), :

$("body").mouseup(function(){

. .

You will need to specifically remove any handlers by calling

$("body").unbind("mouseUp");
+1
source

All Articles