šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Javascript addEventListener will not duplicate named functions

Let's take the classic use of the anonymous function as an event listener. If we bind the same content multiple times to the same event, then it will be called multiple times.

const getData = () => alert('fetching data from server!')
document.getElementById("anonymous").addEventListener(
  'click', () => getData() );
// it another file from a galaxy far far away
document.getElementById("anonymous").addEventListener(
  'click', () => getData() );

In small codebases, it is easy to avoid this but in large ones, these things can happen.

However, the duplication call will not take place if we use a named function as an event listener.

const myNamedLister = () => getData()
document.getElementById("named").addEventListener(
  'click', myNamedLister );
document.getElementById("named").addEventListener(
  'click', myNamedLister );

Alongside making the code more readable using named functions in addEventListener lister can also protect us from strange bugs in large codebases.

Also when you add an event listener to mutiple elements in Javascript named functions may be a good tool.

See the Pen
Named functions in addeventlistener
by JS Craft (@js-craft)
on CodePen.

PS: you can also use full Javascript objects with addEventListener.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *