Reputation: 1780
When I load jQuery dynamically with AJAX, elements with existing events fire multiple times.
Basically I have one file called 'myjs.js' which hold All my jQuery and is included when the page is loaded therefore setting up events and such for elements.
Now when a user triggers an event like posting a new comment, it sends off (via Ajax) the comment, then it returns a page with the new comment, edit comment, reply etc. Obviously when myjs.js
was first loaded it didn't create any events for the newly loaded elements. Therefore I include myjs.js
in the page returned with AJAX.
As the myjs.js
has already been loaded with the page, when the Ajax page is returned with myjs.js
included, it adds another event to the elements that have already been loaded with the page.
I have already tried
$('*').unbind();
But this caused some strange effects.
So any ideas on loading jQuery dynamically while not affecting any events which already exist for elements?
Upvotes: 1
Views: 1667
Reputation: 43823
Without seeing the jQuery code, I suspect that the selectors being used to bind behaviour are too generic so as you have discovered, all existing elements plus the newly loaded elements are matched each time:
You could use more specific binding in the JavaScript returned in the AJAX response to add behaviour only to the newly loaded elements.
However, returning the same JavaScript for each AJAX request is inefficient as the browser cannot cache. Ideally you should try and load the JavaScript on the main page once and then rely on jQuery to do .live()
binding automatically for the newly loaded elements. This is also known as event delegation - .delegate()
Note that as of jQuery 1.7 these methods have been deprecated in favour of a more concise event binding infrastructure - the .on()
Upvotes: 2