stackunderflow
stackunderflow

Reputation: 3873

jQuery on click event binding

if using the following code:

$("#element").on('click', function(){
   alert("clicked!");
});

$("#element").on('click', function(){
   alert("clicked!");
});

it is well known that the click event will fire twice. because it was bound with the method on() and no unbinding with off() followed.

Now my question is

why on this page the click event method is registered only once no matter how many times you click the binding button??

<script>
function flash() {
  $( "div" ).show().fadeOut( "slow" );
}
$( "#bind" ).click(function() {
  $( "body" )
    .on( "click", "#theone", flash )
    .find( "#theone" )
      .text( "Can Click!" );
});
$( "#unbind" ).click(function() {
  $( "body" )
    .off( "click", "#theone", flash )
    .find( "#theone" )
      .text( "Does nothing..." );
});
</script>

I thought that is because the on() method was binding to a named function not anonymous function. but I tested it on jsbin here and it failed ? can any one give me a hint of what am I missing here?

Upvotes: 1

Views: 197

Answers (2)

JohnB
JohnB

Reputation: 13713

The click method is actually registered and called several times, but each of the several event handlers does the same thing, namely fading out the button. You visually cannot notice the multiple calls, as the multiple "fadings" happen (quasi-)synchronously (are controlled by an internal timer), i.e. jQuery does not wait until the button has completely disappeared before continuing with the program. The second handler is called while the button is still visible.

If there are several identical handlers registered, a single call of off() removes them all at once. If you add $("#b").off ('click', doIt) at the end of your own example, you will see that your button does not do anything anymore.

  $("#b").on('click', doIt);

  $("#b").on('click', doIt);

  $("#b").on('click', doIt);

  $("#b").on('click', doIt);

  $("#b").off('click', doIt); // removes all event handlers that are equal (===) to doIt

  // hence now no event handler is registered to #b anymore

Upvotes: 2

Look at this example: JSFiddle. The same code as in jQuery docs but with small modification:

function flash() {
    $("div").show().fadeOut("slow");
    alert('hi');
}

It shows how on works - exactly the same way as you've described. Called by click function in the documentation don't show multiple binding. Then off turns off all assigned click handlers.

Upvotes: 2

Related Questions