Skip to content

Latest commit

 

History

History
62 lines (41 loc) · 1.35 KB

prefer-add-event-listener.md

File metadata and controls

62 lines (41 loc) · 1.35 KB

Prefer addEventListener and removeEventListener over on-functions

Enforces the use of addEventListener and removeEventListener over their on counterparts. For example, foo.addEventListener('click', handler); is preferred over foo.onclick = handler; for HTML DOM Events. There are numerous advantages of using addEventListener. Some of these advantages include registering unlimited event handlers and optionally having the event handler invoked only once.

This rule is fixable (only for addEventListener).

Fail

foo.onclick = () => {};
foo.onkeydown = () => {};
foo.bar.onclick = onClick;
foo.onclick = null;

Pass

foo.addEventListener('click', () => {});
foo.addEventListener('keydown', () => {});
foo.bar.addEventListener('click', onClick);
foo.removeEventListener('click', onClick);

Options

excludedPackages

"unicorn/prefer-add-event-listener": ["error", {"excludedPackages": ["koa", "sax"]}]

This option lets you specify a list of packages that disable the rule when imported. By default, koa and sax are listed.

With koa, this would still pass:

const Koa = require('koa');
const app = new Koa();

app.onerror = () => {};