Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent events from being bound multiple times

Tags:

jquery

 $('.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?

like image 904
Antony Carthy Avatar asked Jun 09 '09 08:06

Antony Carthy


2 Answers

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.

like image 118
Fenton Avatar answered Sep 22 '22 12:09

Fenton


If using jQuery >= 1.7 you can use .on()/.off() API in conjunction with an event namespace. In this example .off() is called immediately to ensure previous events (of any kind) with the namespace are un-bound:

$("form")
    .off(".validator")
    .on("keypress.validator", "input[type='text']", validate);

It's quite a flexible API so you can be very specific if you need to be:

$("form")
    .off("keypress.validator", "input[type='text']", validate)
    .on("keypress.validator", "input[type='text']", validate);

The docs: http://api.jquery.com/off/

like image 45
Pete B Avatar answered Sep 19 '22 12:09

Pete B