I am defining a d3.js script for my module like this:
test:
js:
js/test.js: {}
dependencies:
- mymodule/d3
- core/drupalSettings
d3:
remote: https://d3js.org
version: "4.x"
license:
name: BSD
url: https://opensource.org/licenses/BSD-3-Clause
gpl-compatible: true
js:
https://d3js.org/d3.v4.min.js: { type: external, minified: true }
In my controller, I am sending my data (in $data
) to the script, like this:
$page[] = array(
'#markup' => 'foo',
'#attached' => array(
'library' => array(
'mymodule/test',
),
'drupalSettings' => array(
'mymodule' => array(
'test' => array(
'data' => $data,
),
),
),
)
);
It's working fine, but I've noticed that most js files in core have a wrapper - there is some information here.
Should I be using a wrapper for my script? and if so, what should the wrapper be? and why?
There is no jQuery in my script:
(function (Drupal, drupalSettings, d3) {
Drupal.behaviors.mymoduleTest = {
attach: function (context, settings) {
const data = JSON.parse(drupalSettings.mymodule.test.data);
...
console.log(data);
}
};
})(Drupal, drupalSettings, d3);
I'm wrapping my code, with these three lines top an bottom, but I don't understand if I need any of it?