Please don't litter EventListeners

Clean up after yourself!

Photo by Cam Bradford on Unsplash ​​​​​​​

Javascript EventListeners are a great tool and easily introduced in a template, a fragment or any other frontend component.

It's quick to write

window.addEventListener("scroll", doSomething); 

and something will be done.

What is easily missed is that Liferay runs your code in an SPA environment - which means that your page typically does not fully reload. Which means that your eventListeners stack up every time this fragment is included on a page that you navigate to.

Try it out by implementing

function doSomething() {
  console.log("doing something");
}

and then navigate to a page with this as eventlistener multiple times. The first time, you'll see one message when you scroll. The second time two messages, and so on.

How not to litter?

Easy, add

Liferay.on('beforeNavigate', function(event) { 
  window.removeEventListener("scroll", doSomething); 
​​​​​​​});

for every added EventListener (of course: adapt to the actual event you're handling).

Can you help me with that?

Of course.

If you're following me for a while, you'll have heard me pushing Healthchecks. You should really try them out. (Shameless plug, I know)

The next version will run through all fragments in your system and count&compare the number of addEventListener and removeEventListener occurrences in a fragment's Javascript. Yes - that simple.

And if this very crude counting is not enough, you'll be able to add a comment to your JS code to state that the mismatch is expected - e.g. if the check complains about finding 3 addEventListener occurrences but 2 removeEventListeners, add this line to your Fragment's JS:

// @SuppressWarning EventListener 3 2

(write it exactly like that, one space, capitalization matters, but of course with your specific numbers)

And if you wonder why I'm so specific: This blog article will be linked from the healthcheck as documentation - so I need a URL for it before I can commit and publish the plugin


      

Blogs