Is it better to bind/unbind events or to use a conditional (jQuery)
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 t开发者_Go百科he 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")
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.
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.
精彩评论