olefredrik / FoundationPress

FoundationPress is a WordPress starter theme based on Foundation 6 by Zurb
https://foundationpress.olefredrik.com
MIT License
2.7k stars 869 forks source link

JS function with global scope (not sure if it is a software or meatware problem) #1263

Closed Larzans closed 5 years ago

Larzans commented 6 years ago

I am trying to make a function available at the global scope but i can't get it to work. In my app.js i added the following lines

function Test() {
  console.log('Test called');
}
export {Test};

But the function is not available when i try to call it from the global scope. What am i missing here?

I also tried various permutations of the export, some of which created compile errors, some didn't, but none worked...

conorbarclay commented 6 years ago

Where are you trying to call this function? Apart from being exported, you need to be sure to import it in to whatever file you're trying to call it from.

Also, I would suggest creating a new file for your function and then exporting it from there, rather than cluttering up your app.js.

src/assets/js/modules/test.js:

function test() {
  console.log('hello');
}

export default test;
src/assets/js/app.js:

import test from './modules/test';
test(); // outputs 'hello' in console
Larzans commented 6 years ago

As i said, i need to define a function that is available at the global scope.

The concrete use case is the callback function for the google maps initialisation.

For that i need a function to be available directly at the global scope without needing to import it first.

But thinking about it now i assume that this is not possible with the app.js file as it is a module itself, so i guess i just have to include a plain js file into the page which contains the standard function definition without any ES6 module magic.

Any other ideas though for that use case?

conorbarclay commented 6 years ago

For a Google Maps callback specifically, I'm curious as to what's preventing you from doing all the work within app.js, as opposed to in the global scope. You can always localize variables/render them via PHP to make them available to your app.js (location info, lat/long, etc.).

Obviously without knowing more about your context, it's hard to say - but here's my typical Google Maps starting point. It's a pretty minimal example, but hopefully it gives you some ideas: https://gist.github.com/conorbarclay/51164814aef573a2700edcdd5a7b57c9

JPOak commented 6 years ago

@conorbarclay that's a nice little snippet with ACF integration. Thanks! Caring is sharing.