Skip to content

Commit 813b56e

Browse files
authored
prefer-add-event-listener: Add warning in docs (#2188)
1 parent 54da9ca commit 813b56e

File tree

1 file changed

+3
-1
lines changed

1 file changed

+3
-1
lines changed

docs/rules/prefer-add-event-listener.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@
99

1010
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`](https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick/35093997#35093997). Some of these advantages include registering unlimited event handlers and optionally having the event handler invoked only once.
1111

12-
This rule is fixable (only for `.addEventListener()`).
12+
In most cases, it is safe to replace the `on`-function with the corresponding `addEventListener` counterpart, which is why this rule contains a fixer that swaps it automatically for you. For example, you might be assigning some static functionality to a UI button when the page first loads, and in this context, the functionality of the two would be equivalent.
13+
14+
However, __if you are assigning a listener in a dynamic context, then this rule's auto-fixer will make your code bugged__. This is because the `on` assignment replaces the current listener, but the `addEventListener` adds an additional listener in addition to the ones that are already assigned. For example, if you are dynamically updating the functionality of a button as new data comes in, then using `addEventListener` would not work, since it would cause N functions to be invoked for every previous data state. In this context, you should probably disable this lint rule and use the `on` form, since [removing existing event listeners is not possible](https://stackoverflow.com/questions/9251837/how-to-remove-all-listeners-in-an-element).
1315

1416
## Fail
1517

0 commit comments

Comments
 (0)