0

What's the "well threaded path" for handling JavaScript events in dynamically loaded (ajax) pages.

I have an app which has a tab bar controller that pulls in the sub-views through ajax, and these views have their own js, which is fine the first time round, but if someone were to use the app for a long time and cycle through all the tab views repeatedly, the events would keep getting bound over and over again which seems horribly inefficient, especially considering that these sub-views might have their own sub-views which they manage, some of which could have lots of event handlers.

What are some of more elegant approaches to solving this? (BTW, I'm using jQuery)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
lmirosevic
  • 15,787
  • 13
  • 70
  • 116
  • Use on() and off() functions instead. Related: http://stackoverflow.com/questions/209029/best-way-to-remove-an-event-handler-in-jquery – jfrej May 18 '12 at 12:33

1 Answers1

0

It depends on the scenario, and you didn't show even one line of code, but you can use unbind before you bind new callback:

$('#foo').unbind('click').click(handler);
...
$('#foo').unbind('click').click(handler)
...
$('#foo').unbind('click').click(handler)
...

$('#foo').click(); // handler fire one time only.
gdoron
  • 147,333
  • 58
  • 291
  • 367