Some events are added repeatedly #236

Closed
opened 2021-04-29 04:30:27 -05:00 by ghost · 1 comment
ghost commented 2021-04-29 04:30:27 -05:00 (Migrated from github.com)

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

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 ```javascript 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 2021-04-29 05:15:54 -05:00 (Migrated from github.com)

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.

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.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: iLoveElysia/pjax#236