@@ -50,25 +50,55 @@ function initAll(config) {
50
50
const $scope = config . scope ?? document
51
51
52
52
components . forEach ( ( [ Component , config ] ) => {
53
- const $elements = $scope . querySelectorAll (
54
- `[data-module=" ${ Component . moduleName } "]`
55
- )
53
+ createAll ( Component , config , $scope )
54
+ } )
55
+ }
56
56
57
- $elements . forEach ( ( $element ) => {
58
- try {
59
- // Only pass config to components that accept it
60
- 'defaults' in Component
61
- ? new Component ( $element , config )
62
- : new Component ( $element )
63
- } catch ( error ) {
64
- console . log ( error )
65
- }
66
- } )
57
+ /**
58
+ * Create all instances of a specific component on the page
59
+ *
60
+ * Uses the `data-module` attribute to find all elements matching the specified
61
+ * component on the page, creating instances of the component object for each
62
+ * of them.
63
+ *
64
+ * Any component errors will be caught and logged to the console.
65
+ *
66
+ * @template {CompatibleClass} T
67
+ * @param {T } Component - class of the component to create
68
+ * @param {T["defaults"] } [config] - config for the component
69
+ * @param {Element|Document } [$scope] - scope of the document to search within
70
+ */
71
+ function createAll ( Component , config , $scope = document ) {
72
+ const $elements = $scope . querySelectorAll (
73
+ `[data-module="${ Component . moduleName } "]`
74
+ )
75
+
76
+ $elements . forEach ( ( $element ) => {
77
+ try {
78
+ // Only pass config to components that accept it
79
+ 'defaults' in Component
80
+ ? new Component ( $element , config )
81
+ : new Component ( $element )
82
+ } catch ( error ) {
83
+ console . log ( error )
84
+ }
67
85
} )
68
86
}
69
87
70
88
export { initAll }
71
89
90
+ /* eslint-disable jsdoc/valid-types --
91
+ * `{new(...args: any[] ): object}` is not recognised as valid
92
+ * https://github.com/gajus/eslint-plugin-jsdoc/issues/145#issuecomment-1308722878
93
+ * https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/131
94
+ **/
95
+
96
+ /**
97
+ * @typedef {{new (...args: any[]): unknown, defaults?: object, moduleName: string} } CompatibleClass
98
+ */
99
+
100
+ /* eslint-enable jsdoc/valid-types */
101
+
72
102
/**
73
103
* Config for all components via `initAll()`
74
104
*
0 commit comments