views:

31

answers:

2

Ok, this is a performance question I guess.

I have a slider with two navigation links (next and previous) and when the slider gets to the end of the row I am currently unbinding the next button, then binding again when it goes in the other direction. I am performing the same operation for the next button, but reversed.

the code for the next button would look something like this

if (at end of slider) {
  nextBtn.unbind("click")
} else if (not already bound) {
  nextBtn.bind("click",clickHandler)
}

So... Is it better do it this way or to have a conditional in the click handler to check for $.data(nextBtn,"state","on") or $.data(nextBtn,"state","off")

+2  A: 

I would say the conditional statement.

Simply put every time you bind and unbind an event from what I gather jquery has to create and manage an entire new object.

Hailwood
+2  A: 

If you're using an actual <button> then you can just set the disabled attribute to true and not have to worry about anything in your event handler, since the event will never be triggered. This also has the added benefit of adding a visual aide to tell the user that the button in question is no longer functional (which you should be doing regardless of the chosen button representation).

Otherwise, I usually keep with the mindset of staying out the DOM as much as possible, and that includes bind and unbinding events. With this in mind, I would bind the events once, and check whatever condition you have within the event handler.

Justin Johnson
Hmm, perhaps (on reflection) button was a poor choice of words. It's actually a dynamically created link so has no disabled state. I take your point though. I'll take a look at trying to use a conditional for this, though using $.bind to test on probably isn't a goer either
Ninjabiscuit