How to deal with eslint complaints about used-vars for functions called from dom events

Viewed 61

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?

1 Answers

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.

Related