2

When the function is called from an event such as a mouse click on a button or link, eslint complains about unused-vars because the only reference is the attached event in the HTML page.

I like the unused-vgars warning otherwise.

My current approach is to disable the lines with the eslint-disable line comment, i.e.

const addStreetAddressLine = () => { // eslint-disable-line no-unused-vars

but now I am sprinkling that big comment throughout my code - 3 functions so far.

Is there another approach that is a bit cleaner?

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497

1 Answers1

2

It would be better to attach the listeners using Javascript. Inline handlers have way too many problems: they have crazy scoping rules, require global pollution to work, and can require ugly escaping when the function needs to be called with a string argument.

Use addEventListener instead. Eg, change

<span onclick="addStreetAddressLine()">

to

<span class="someSpan">
document.querySelector('.someSpan').addEventListener('click', addStreetAddressLine);

That will get rid of the linter warning and make your code more maintainable.

The someSpan is just there to give you a way to select the element. You don't have to add a class, you just need some way to precisely select the element.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Personally, I don't like IDs since they [pollute the top level](https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables) unnecessarily, which can result in bugs. I'd prefer to select it by using already-existing attributes of it or its ancestors. This is almost always possible. If not, you can add a class, like I did there. Or you can add an ID instead of a class, but a class may be a better choice. – CertainPerformance Mar 22 '20 at 23:07
  • Hmmm, excellent point. How about a `data-` attribute. Maybe like `data-address-form-addStreetAddressLine` – Michael Durrant Mar 22 '20 at 23:37