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 *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X