defunkt / jquery-pjax

pushState + ajax = pjax
https://pjax.herokuapp.com
MIT License
16.73k stars 1.97k forks source link

Bug when popstate unbinding events ? #604

Closed Eschwinm closed 7 years ago

Eschwinm commented 8 years ago

Good afternoon,

I have been using PJAX a while and I have lots of custom made plugins. Now when I put all the initializing of my plugins in an init function and execute that function on document ready and pjax:ready everything works fine. However, on popstate it will need to reinitialize all plugins because it's getting buggy and broken. When I do so, all my plugins re-initialize and all events will be attached twice. For example when I click a button with an ajax call behind it, the ajax call will fire twice.

Is there any way I can prevent this from happening ? Because simply unbinding events does not work for me, or I'm doing it incorrectly.

It would be nice if someone could share their experience on how the popstate works and how I can prevent this from happening with my custom plugins (also other public plugins without destroy function will break on popstate).

Thanks in advance!

mislav commented 7 years ago

The correct approach would be to only re-initialize your plugins within the context of the pjax container, not the entire page. That way you avoid double-initializing some widget elsewhere on your page.

$(document).on('pjax:end', function(event) {
  $(event.target).reinitializeMyPlugin()
})