Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent JavaScript modules being initialised multiple times #2762

Closed
querkmachine opened this issue Aug 12, 2022 · 1 comment
Closed

Prevent JavaScript modules being initialised multiple times #2762

querkmachine opened this issue Aug 12, 2022 · 1 comment
Labels
feature request User requests a new feature javascript

Comments

@querkmachine
Copy link
Member

querkmachine commented Aug 12, 2022

Related component

All components with JavaScript.

Context

Currently, we don't have anything to prevent the JavaScript module aspect of components being initalised multiple times. This can create a broken user experience where this has happened (either accidentally or intentionally), as multiple event bindings will be created and HTML elements will be created or manipulated multiple times.

Alternatives

It may be possible to work around this issue using the scope option of initAll, however this doesn't directly prevent duplicate initialisations.

Additional information

This functionality may come in useful with our current work relating to localisation and programatic APIs.

For example, a service developer may only want to pass configuration options to a specific instance of a component, but use the default options for all other components. In attempting to do so, they may write something like this:

new window.GOVUKFrontend.Accordion($element, { config }).init()
window.GOVUKFrontend.initAll()

However, unless the developer takes care to remove the data-module attribute from the custom instance (which isn't possible if using our Nunjucks macros), this will initialise the same Accordion twice—resulting in multiple buttons and event handlers being created.

The simplest way to do this is probably by recording which elements have already been initialised and checking against that record when components are initialised again. This could be done by adding a data-* attribute to the element, recording it in the element's dataset (this approach won't work in IE8–10), or maintaining a persistant array of initialised elements.

@querkmachine
Copy link
Member Author

Duplicate of #1127. D'oh!

@querkmachine querkmachine closed this as not planned Won't fix, can't repro, duplicate, stale Aug 12, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature request User requests a new feature javascript
Projects
None yet
Development

No branches or pull requests

1 participant