Cross-file JavaScript variables

From GT-MP
Jump to: navigation, search

Cross-file JavaScript variables

If your resource includes multiple .js files for client-side code, you might want to reference a variable/function in one file, inside another.
This can be done through the resource. global variable.

After onResourceStart has triggered, a global variable gets created that contains the global namespaces of all .js files included in the meta.xml script tags.

Example

Imagine you have this kind of file structure:

-- my-resource
 |-- script1.js
 |-- script2.js
 |-- meta.xml

script1.js contains:

// script1.js
function myMethod() {
    // ...
}

And your meta.xml contains

<script src="script1.js" type="client" lang="javascript" />
<script src="script2.js" type="client" lang="javascript" />

From script2.js you'd be able to call myMethod() in script1.js by doing the following:

// script2.js
API.onResourceStart.connect(function() {
    resource.script1.myMethod();
});

Notes

File names like my.first.script.file.js get the .'s replaced with _'s.
This script's namespace would end up like this: resource.my_first_script_file.myMethod()