Reputation: 11
My main issue here is when using require.js my function is no longer Global. So when I call it from my phtml file it is not being found. Any idea what the correct way to make a function inside my js file global? I've tried multiple methods/answers I found online but nothing seems to be working out. Any suggestions?
Here is my js file
define([
'jquery'
], function ($) {
return function (config) {
console.log(config);
}
function initMap() {
console.log('initMap is being called');
}
});
My requirejs-config.js file:
var config = {
map: {
'*': {
'gslMap': ['Gauge_StoreLocator/js/app']
}
}
};
My phtml file: The callback function "initMap" is being called at end
<script async defer src="https://maps.googleapis.com/maps/api/js?key=<?php echo $this->getGoogleApi(); ?>&callback=initMap">
Upvotes: 1
Views: 6271
Reputation: 151401
If you must make your initMap
function global, you can do it by deliberately leaking it into the global space:
define([
'jquery'
], function ($) {
return function (config) {
console.log(config);
}
function initMap() {
console.log('initMap is being called');
}
// Deliberately leak initMap into the global space.
window.initMap = initMap;
});
Note, however that RequireJS is always operating asynchronously when used in the browser. So if you just plop your script
tag somewhere and hope for the best, you're going to run into trouble. If it is added dynamically by code that loads you module with initMap
first, then you'll be fine.
Note that map
does not take arrays. paths
on the other hand does accept arrays as values but I'm not seeing the point of an array of just one element. (Arrays are meant to provide fallbacks.) The reason RequireJS does not fail loudly due to the array you give in your map
is that in JavaScript ["foo"].toString() === "foo"
and there is an implicit call to .toString()
in the code that processes the values of map
so RequireJS sees your array in the same way as if you had just put the single string it contains instead of the array. If you try with an array of more than one element, you'll get into trouble.
Upvotes: 2