MoOx / pjax

Easily enable fast Ajax navigation on any website (using pushState + xhr)
MIT License
1.43k stars 124 forks source link

Some events are added repeatedly #236

Closed ghost closed 3 years ago

ghost commented 3 years ago

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](https://user-images.githubusercontent.com/47672657/116530238-655b8680-a910-11eb-9ac2-e1949894e0b8.png)
robinnorth commented 3 years ago

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.