I want to create a custom module, to do consume an API, and I need to create a JavaScript function to return API data, and call this JavaScript function from another JavaScript file, in another custom module.
Sure ! Here an example :
In the first module, name test1 in my_function javascript file :
(function ($, Drupal, drupalSettings) {
'use strict';
Drupal.behaviors.test1_my_functions = Drupal.behaviors.test1_my_functions || {};
Drupal.behaviors.test1_my_functions = {
attach: function (context) {
},
targetFunction: function() {
console.log('Use it !');
}
}
})(jQuery, Drupal, drupalSettings);
Then in the module test2 in example javascript file :
(function ($, Drupal, drupalSettings) {
'use strict';
Drupal.behaviors.test2_example = Drupal.behaviors.test2_example || {};
Drupal.behaviors.test2_example = {
attach: function (context) {
Drupal.behaviors.test1_my_functions.targetFunction();
}
}
})(jQuery, Drupal, drupalSettings);
Don't forget to define the dependency in info.yml for module "test2" with "test1" in "test2.info.yml" and the dependency in javascript library "test2.libraries.yml"
example:
js:
js/example.js: {}
dependencies:
- core/jquery
- core/jquery.once
- core/drupal
- core/drupalSettings
- test1/my_functions