Skip to content

Latest commit

 

History

History
74 lines (53 loc) · 1.75 KB

prefer-add-event-listener.md

File metadata and controls

74 lines (53 loc) · 1.75 KB

Prefer .addEventListener() and .removeEventListener() over on-functions

This rule is part of the recommended config.

🔧 This rule is auto-fixable.

Enforces the use of .addEventListener() and .removeEventListener() over their on-function 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 = () => {};