Skip to content

Commit

Permalink
docs: add prefer-add-event-listener warning
Browse files Browse the repository at this point in the history
  • Loading branch information
Zamiell committed Aug 18, 2023
1 parent 6d15a02 commit 3dc6aee
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion docs/rules/prefer-add-event-listener.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@

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.

This rule is fixable (only for `.addEventListener()`).
In most cases, it is safe to replace `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.

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).

## Fail

Expand Down

0 comments on commit 3dc6aee

Please sign in to comment.