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 subviews 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 subviews might have their own subviews 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)

lms
  • 14,269
  • 12
  • 64
  • 113
  • 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 is supporting Monica
  • 136,782
  • 49
  • 273
  • 342