jQuery: Preventing an event from being attached more than once?
Posted
by Evan Carroll
on Stack Overflow
See other posts from Stack Overflow
or by Evan Carroll
Published on 2010-06-02T17:15:25Z
Indexed on
2010/06/02
17:24 UTC
Read the original article
Hit count: 184
jQuery
Essentially, I have an element FOO
that I want when clicked to attach a click event to a completely separate set of elements BAR
, so that when they're clicked they can revert FOO
to its previous content. I only want this event attached once.
When FOO
is clicked, its content is cached away in $back_up
, and a trigger is added on the BAR
set so that when clicked they can revert FOO
back to its previous state. Is there a clever way to do this? Like to only .bind()
if the event doesn't already exist?
$('<div class="noprint little check" />').click( function () {
var $warranty_explaination = $(this).closest('.page').children('.warranty_explaination');
var $back_up = $warranty_explaination.clone(true);
$(this).closest('.page').find('.warranties .check:not(.noprint)').click( function () {
/* This is the code I don't want to fire more than once */
/*, I just want it to be set to whatever is in the $back_up */
alert('reset'); $warranty_explaination.replaceWith( $back_up )
} );
$warranty_explaination.html('asdf')
} )
Currently, the best way I can think to do this is to attach a class, and select where that class doesn't exist.
© Stack Overflow or respective owner