tags:

views:

137

answers:

2

I have a situation where I need to bind a click event to an object multiple times.

For instance:

for(i=0;i<=100;i++){
    $myObject.click(function(){
         window.location = "myurl"+i+".html";
    })
    ...do other stuff...
}

Via that markup, does $myObject end up with 100 click events attached to it? Should I be unbinding the click event first each time?

for(i=0;i<=100;i++){
    $myObject.unbind('click').click(function(){
         window.location = "myurl"+i+".html";
    })
    ...do other stuff...
}
+1  A: 

You would be binding 100 click events in the first call, and it would set the window location from myurl0.html - myurl100.html on a single click. (EDIT: I didn't test this, though; it might be creating a closure and thus would only open myurl100.html.)

The second would only open myurl100.html.

In general, it's best to unbind events that are no longer necessary.

Are you looking for something like one, which fires once and is unbound?

ajm
"In general, it's best to unbind events that are no longer necessary." <-- that's pretty much what I was asking. Thanks for the answer! I assume applying a click event to the same object over and over without unbinding was a bad idea.
DA
A: 

According to this article, live() method will be faster than bind()

Boris Guéry