jroberts
jroberts

Reputation: 449

Unbind, or Reset all jQuery Events

I have a page that I have a product configurator on, this configurator uses ajax .load to load up the configurator for different products.

If someone configures a product, clicks submit, the product is added, if the user selects the configurator again, and loads that same product, all of the events for the configurator are doubled. Meaning, all the events fire twice...

What would be the best way to reset these events, or prevent these events from firing more than once?

Upvotes: 3

Views: 6561

Answers (3)

jroberts
jroberts

Reputation: 449

I am using .live().

I found the easiest solution for me was to put a .die() before each .live() statement.

Example:

$('.add').die();
$('.add').live(...............

http://api.jquery.com/die/

Upvotes: 0

Nope
Nope

Reputation: 22329

I don't know what syntax you use to bind but if you are using jQuery 1.7 using on() you can this:

$("#myButton").off("click").on("click", function(){
    // ....
});

That will ensure all click events are unbound first and then your click event is bound. However, this comes with risks, if you have many click events bound through namespaces they might also get removed even if that was not your intention.

If an event is using a namespace it may look like this:

$("#myButton").off("click.myNamespace").on("click.myNamespace", function(){
    // ....
});

If you need to have an event bound and only want to use it ones and then have it unbind automatically you can use one() like this

$("#myButton").one("click", function(){
    // ....
});

Just to clarify you can off course just use off() or unbind() by themselves without chaining them to on() or bind(), etc.. Word of caution though on unbind() if you happen to use live() for your bindings. One of the many drawbacks of live() is:

The .live() method interacts with other event methods in ways that can be surprising, e.g., $(document).unbind("click") removes all click handlers attached by any call to .live()!

Additional Resources

click() - is similar to bind
bind() - preferred binding for static elements pre jQuery 1.7
live() (don't use) - deprecated since 1.7 but don't use pre 1.7 either
delegate() - preferred binding for dynamic elements pre jQuery 1.7
on() - preferred binding for static/dynamic elements since jQuery 1.7

Upvotes: 3

MrOBrian
MrOBrian

Reputation: 2189

Depending on how you are binding the events, you will want to use .unbind() or .off() (if you are using .live() it is deprecated and you should switch to .on())

jQuery has a nice page on Namespaced Events which illustrates how to only unbind the event handlers you added.

Upvotes: 0

Related Questions