Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Publisher Tag, how to remove event listener from Service

Tags:

gpt

There seem to be several questions on how to register events to a gpt service:
Google Publisher Tag registering to Events
registering to events with google publisher tag

How to do this is clearly defined in the documentation:
googletag.pubads().addEventListener('eventName', callbackFn);

I add my event to the service when the component (React) mounts inside the callback function of window.googletag.cmd.push as described in this tutorial by Google.

Now the problem is that every time I change page, more event listeners are added to the service. I can make sure only one event listener executes on the actually existing slots by using this method (from the documentation):

googletag.pubads().addEventListener('impressionViewable', function(event) {
  if (event.slot == targetSlot) { // will only run on target slot
    // Slot specific logic.
  }
});

But more an more event listeners will remain active and keep on executing (without executing the code within the if-statement).

Now, I assumed google would have implemented something like this (to run on componentWillUnmount):
googletag.pubads().removeEventListener('eventName', callbackFn);

But it doesn't exist in the documentation and I can't seem to find any way to remove active event listeners from the service?

like image 477
MrJalapeno Avatar asked May 10 '19 14:05

MrJalapeno


People also ask

Can you remove event listeners?

Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.

Why should you remove event listeners once they are no longer used?

The event listeners need to be removed due to following reason. Avoid memory leaks, if the browser is not handled it properly. Modern browsers will garbage collect event handlers of removed DOM elements but it is not true in cases of legacy browses like IE which will create memory leaks.

What happens if you don't remove event listeners?

The main reason you should remove event listeners before destroying the component which added them is because once your component is gone, the function that should be executed when the event happens is gone as well (in most cases) so, if the element you bound the listener to outlasts the component, when the event ...


1 Answers

So I went with this:

let eventListnerCreated = false;
if(!eventListnerCreated) {
    eventListnerCreated = googletag.pubads().addEventListener("slotRenderEnded", function(event) {
          // blablabla
    });
}

Not clean. But will work.

I know this doesn't solve the original issue of removing the event listener, but this will let's not create event listeners again and again.

like image 141
Asim K T Avatar answered Oct 26 '22 14:10

Asim K T