tags:

views:

77

answers:

2
 $('.ajax').click
 (        
    function()
    {
        // If been bound then we need to return here.
        alert(':D');
    }
 )

 $('.ajax').click
 (
    function()
    {
        // If been bound then we need to return here.
        alert(':D');
    }
 )

In this case, I have called duplicate code. How do I detect if the event has been bound to prevent it from triggering two alert boxes?

+1  A: 

try unbinding it before binding:

$(".ajax").unbind("click").click( 
      function () { 
    alert("Hello"); 
  } );

read this for some more information.

TheVillageIdiot
This will unbind all click events, not just the specified event. I've added an example that will only unbind the event you don't want to duplicate, which means other events will still fire.
Sohnee
+2  A: 

There's a really good way to do this in jQuery.

Here's an example.

function alertEvent() {
   alert(":D");
}
$(".ajax").bind("click", alertEvent);
//When you want to ensure it won't happen twice...
$(".ajax").unbind("click", alertEvent);
$(".ajax").bind("click", alertEvent);

This method will only remove the event you specify, which makes it ideal for what you want to do.

Sohnee
How can one pass the click arguments e with that? Can I go $(".ajax").bind("click", alertEvent(e)); ?
Antony Carthy
define the function as "function alertEvent(e)" to get the event argument.
mcrumley
Thanks @Sohnee, yes this is more elegant solution!
TheVillageIdiot