简体   繁体   中英

event handler binding and unbinding with ajax loaded pages

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM