MoOx/pjax

Some events are added repeatedly

awnawnawn opened this issue · 1 comments

I used the plug-in for image viewing, In the plug-in, the window resize event is added. When I switch several pages, I find that the resize event has been added repeatedly.

Make a demo

example.js

function event(){
  document.addEventListener('resize',function (){
    console.log('add event');
  })
}

document.addEventListener("pjax:success", function() {
  console.log("Event: pjax:success", arguments);

  // Init page content
  initButtons();
  event();
});

document.addEventListener("DOMContentLoaded", function() {
  // Init Pjax instance
  pjax = new Pjax({
    elements: [".js-Pjax"],
    selectors: [".body", "title"],
    cacheBust: true
  });
  console.log("Pjax initialized.", pjax);

  // Init page content
  initButtons();
  event();
});

After clicking to switch the page several times, the event is added repeatedly

sd28-52

This is because your "pjax:success" event listener calls your event function that adds a "resize" listener, meaning that every time you load a new page with Pjax, you add a new listener.

You should either only call this function once, or remove any previously-added "resize" listeners before adding a new one.