Call function from another js file when using iife pattern? - javascript

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:
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>

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.

I think this should work.
ValidationNamespace().validateIfNameAlreadyExistsInTable(theName);

Related

Pass variable from one Javascript File to the another ( specific situation )

I have 2 different Javascript files.
How to i pass a Javascript variable inside a Jquery document function to another Javascript file.
chat.js
$(document).ready(function () {
var a = "something"
}
to scripts.js
$(document).ready(function () {
console.log(a); //gives undefined
}
index.html
<script type="text/javascript" src="/js/chat.js"></script>
<script type="text/javascript" src="/js/scripts.js"></script>
Notes: i am aware this theres a duplicate but not of this specific situation
I have tried multiple solutions such as globally declare the variable but wont work for me since this is for a socket.
Maybe you can use localStorage?
Try this:
Chat.js
$(document).ready(function () {
var a = "something";
localStorage.setItem('a', a);
}
Scripts.js
$(document).ready(function () {
console.log(localStorage.getItem('a'));
}
In chats.js:
var a;
$(document).ready(function () {
a = "something"
}
In scripts.js:
$(document).ready(function () {
console.log(a); //gives something
}
Either make a global(window) level variable and use it on both js file,
or make global level function and pass the local variable as parameter to global function.

Execute global javascript code anonymously

I have the following html:
<script type="text/javascript" src="before.js"></script>
<script type="text/javascript" src="globalCode.js"></script>
<script type="text/javascript" src="after.js"></script>
The globalCode.js file contains:
function doStuff() {
return 1 + 2;
}
module.export = doStuff();
I want to get the contents of module.export but without letting doStuff() get into the global context.
So basically I would like the following functionality:
var module = {};
(function() {
function doStuff() {
return 1 + 2;
}
module.export = doStuff();
}();
with the restriction that I can not modify globalCode.js and can only use before.js & after.js.
I thought about saving the global object in before.js and restoring it in after.js but I am not quite sure how.

Access a variable defined in a js , from an html page?

I have set a variable in one of my javascript files and i want to access that variable in an html file . How do i do the same?
here us my javascript code(file name is JSUI.js):
JSUI = function () {
this.glistName = null;
this.renderUI = function(list) {
this.glistName = list.listName;
window.location="page2.html";
};
};
var gJSUI = new JSUI();
page2.html:
<body>
<script src="js/JSUI.js"></script>
ListName: <input type="text" id="listName"></input>
</body>
<script type="text/javascript">
if(document.readyState="complete"){
document.getElementById("listName").value = gJSUI.glistName;
}
</script>
Basically page2.html gets loaded when renderUI method of JSUI.js is called and i want to populate a textbox present in page2.html with a variable defined in JSUI.js file .How do I achieve the same?
you have actually created a class but there are some mistakes and the most important : you don't initialize the class itself.
Try this:
JSUI = function () {
this.glistName = null;
this.renderUI = function(list) {
this.glistName = list.listName;
window.location="page2.html";
};
};
And in you page:
if(document.readyState="complete") {
var myobject = new JSUI();
document.getElementById("listName").value = myobject.glistName;
}
There are different methods to achieve the desired result:
1) Set the variable to the global Window object;
2) Use a modular pattern where you export the variable in one js file, and import it in the other (which I'd use). Use AMD (requirejs), commonjs, ES6 modules, ... ;
3) Use the localstorage to store state;
4) Use the DOM to store state;
5) Keep state at the server and use dehydrate to extract state into JS objects to different components when the js gets loaded;
6) Use ajax to get state from the server when the page is loaded and dispatch the state to different components that need it on app bootstrap;

Access variable from another script source

<script src="http://domain.com/source1.js"></script>
<script src="http://domain.com/source2.js"></script>
source1.js
var PICTURE_PATH = "";
var PICTURE_ROOT = base_url+"YOUTAILOR_files/";
var PROGRAM = parseInt("1");
source2.js
if(PROGRAM==3 || PROGRAM==4 || PROGRAM==5)
{
}
I could not access value of program in source2.js..
When you declare var source1Var outside a function you are actually creating a variable on the window object. So you should just be able to access it from source2.js. Just make sure source1.js is before source2.js in the script tags...
If however you're declaring it within a function, it will be private to that function. If you really need to you could set it on window explicitly.
In source1.js
function foo() {
window.source1Var = 3;
}
In source2.js
function bar() {
console.log(source1Var); // this will search window if it cannot find in the local scope.
}
What is the problem you're trying to solve? It is generally better to use some form of dependency injection, event listeners, builder pattern etc. rather than using global variables.
do something like in your first .js
var VAR = {
myvalue: "hai"
};
then call it in second like
alert(VAR.myvalue);
It's easier than you think. If variable is global, you should access it from anywhere.
// source1.js
var colorCodes = {
back : "#fff",
front : "#888",
side : "#369"
};
And in another file:
// source2.js
alert (colorCodes.back); // alerts `#fff`

Add variables to a .js file

I'm looking for a way to post variables in an external .js file.
Something like:
<script type="text/javascript" src="/js/script-starter.js?var=value"></script>
And then I'd like to call var (and thus, value). Is this possible in any way?
Thank you!
Yes, it is possible. You will have to look for all script tags in the DOM (make sure the DOM is loaded before attempting to look in it) using the document.getElementsByTagName function, loop through the resulting list, find the corresponding script and parse the src property in order to extract the value you are looking for.
Something along the lines of:
var scripts = ​document.getElementsByTagName('script');
​for (var i = 0; i < scripts.length; i++)​ {
var src = scripts[i].src;
// Now that you know the src you could test whether this is the script
// that you are looking for (i.e. does it contain the script-starter.js string)
// and if it does parse it.
}​
As far as the parsing of the src attribute is concerned and extracting the query string values from it you may use the following function.
it could be possible if that script is a serverside script that receives the variable in querystring and returns a javascript code as output
How about declaring the variable before script file loading:
<script type="text/javascript">var myVar = "Value"</script>
<script type="text/javascript" src="/js/script-starter.js"></script>
So you can use this variable in your script. Possibly this is one of the easiest ways.
Why don't you put the variables in a hidden a or p
<a id="myHiddenVar" style="display:none;">variables</a>
Then in your .js you access it with
var obj = document.getElementById("myHiddenVar").innerHTML;
or the jQuery style
var obj = $("#myHiddenVar").text();
function getJSPassedVars(script_name, varName) {
var scripts = $('script'),
res = null;
$.each(scripts, function() {
var src = this.src;
if(src.indexOf(script_name) >= 0) {
varName = varName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var string = new RegExp("[\\?&]"+ varName +"=([^&#]*)"),
args = string.exec(src);
if(!args.length) {
res = null;
} else {
res = args[1];
}
}
});
return res;
}
console.log(getJSPassedVars('script-starter.js', 'var'));
in my case my app folder structure is like following:
MyApp/
index.html
jquery.js
my.js
above function is within my.js with console.log and include it within index.html.

Categories