SwedbankPay/design.swedbankpay.com

dg.sheet.init creates multiple addEventListener("keydown"

stepandersen opened this issue · 2 comments

Sheet is adding a new eventListener for keydown (to listen for esc key) every time a dg.sheet.init is called.

If I do this:

dg.sheet.init("my-edit-sheet");
dg.sheet.init("my-create-sheet");

Two eventListeners for keydown will be created, both looping through the _sheets array to close the open sheets.

...
 _sheets.forEach(sheet => sheet.isOpen ? sheet.close() : null);
...

Suggested solution:
Register that document.addEventListener("keydown", e => { is set, and prevent it from registering it again if it has already been set. As long as the sheet are added to _sheets array, the sheet will be closed by that first eventListener.

As a side note, we might also want to prevent _sheets from registering the same sheet twice.

dg.sheet.init("my-edit-sheet");
dg.sheet.init("my-edit-sheet");

Will add two sheets to _sheets, and loop through both of them on e.g. _sheets.forEach(sheet => sheet.isOpen ? sheet.close() : null);.

I added this as a comment since users of the design guide shouldn't actually call init on the same sheet twice. But it might be right to prevent it if they do.

Not sure if this sufficiently resolves your issue, but according to MDN, duplicate eventListeners should still be called once, as long as they are considered identical to eachother

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener() method.

Note, however that when using an anonymous function as the handler, such listeners will NOT be identical, because anonymous functions are not identical even if defined using the SAME unchanging source-code simply called repeatedly, even if in a loop.

(Source: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Multiple_identical_event_listeners)

Some changes to the code will be made to ensure that the eventListeners are considered identical