In my exemple, i have just one function and I call it in phtml on passing the name function as param require(['jquery', 'module'], function($, hello)
and it works fine.
-
Now if i want to return 10 functions for exemple, what is the best way to do that.
-
Did
deps
attributedeps: ["js/go"]
is correct for that instead ofmap
-
I wonder if there is not a way to implemente some js libraire, ie we have to put the lib js content in a file js then we declare it in a some module then the lib content will automatically be rendered without calling all functions one by one.
app/code/Vendor/Module/view/frontend/requirejs-config.js
var config = {
map: {
'*': {
module: 'Vendor_module/js/go',
}
}
};
app/code/Vendor/Module/view/frontend/web/js/go.js
define(['jquery'], function($){
"use strict";
return function hello()
{
alert('hello from function');
}
public function f1()
{
...
}
public function f2()
{
...
}
...
});
app/code/Vendor/Module/view/frontend/templates/file.phtml
<script type="text/javascript">
require(['jquery', 'module'], function($, hello) {
hello();
});
</script>
Best Answer
Rather than return the function you can return an object that contains the functions, you can them call them individually whenever you need.
In this example I have 3 files:
app/design/frontend/Vendor/theme/Magento_Theme/templates/test.phtml
app/design/frontend/Vendor/theme/Magento_Theme/web/js/module-a.js
app/design/frontend/Vendor/theme/Magento_Theme/web/js/module-b.js
Template
Module A
Module B
Screenshot
Alternative method
You can also do it by writing the functions outside an object, then returning only the functions you need. The positive of this method is you only return what you want to be re-usable.
Replace module A from above with this:
Screenshot