nemo_87 nemo_87 - 3 months ago 22
Javascript Question

Call function from another js file when using iife pattern?

Is it possible to call function that is in one js file and it is made public by usage of iife pattern, in another js file?
For example, this is some validationScript.js file:

var ValidationNamespace = function ()
{
var nameValidation = "";
var testValidation = "";

return{
validateIfNameAlreadyExistsInTable : function(currentNameValues)
{
for(var i=0; i < currentNameValues.length ; i++)
{
if(document.getElementById("tbName").value == currentNameValues[i])
{
var nameVal = "Name already exists in table!";
document.getElementById("nameVal").innerHTML = nameVal;
return false;
}
}
document.getElementById("nameVal").innerHTML = "";
return true;
}
};
}();


And I have another file, lets say script.js

Is there some way to call function
validateIfNameAlreadyExistsInTable
from some script.js function?

The problem is that it is undefined when I try to call it:

enter image description here

I have index.html where I am referencing both .js files like this:

<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="validationScript.js"></script>

Answer

Yes, because the IIFE returned an object that exposes the function, and the file saves that object as ValidationNamespace, which is a var declared globally and thus a global variable.

So:

ValidationNamespace.validateIfNameAlreadyExistsInTable(theName);

Re your edit, you probably want to load the scripts in the other order, first validationScript.js then script.js:

<script type="text/javascript" src="validationScript.js"></script>
<script type="text/javascript" src="script.js"></script>

Scripts are loaded and run in the order you give them (unless you use async or defer). So unless your code in script.js is waiting for some other event, it'll run before validationScript.js is loaded.