I was actually going through this link. which explains how we can share global variable across multiple js. but the point is what need to be done if I am getting some variable into one js and need to pass to another one mentioned in same document after the 1st one.
approach which followed was:
Script 1 <script type="text/javascript" src="js/client.js"></script>
body added some hidden input with id myHiddenId, where values are set using client.js
Script 2 <script type="text/javascript" src="js/anotherJS.js"></script>
inside script 2 I am simply using $("#myHiddenId").val(); and using for my purpose.
I want to know whether I am following correct approach, because that hidden field may have some data which client should not get aware of. is there any other way through which I can pass the variable values across the js files ? Since I am at beginner level hence digging up some resources/books but still no luck.
If the client should not be aware of the data then you should not be using client side JavaScript. Any JavaScript executed in the browser can be debugged and viewed by the user.
You should always handle sensitive data on the server side.
Saving the variable in the JavaScript file or in the hidden element makes little difference.
Regarding using variables across files then you should be able to use any variables declared in Script 1 in Script 2 provided they are declared in the root scope and that Script 1 appears before Script 2 in the DOM.
<script> // Script 1
var root_scope = 'This variable is declared at root';
function some_function() {
// Variables not defined at root are subject to the scope they are in
var non_root = 'This is not at root';
}
</script>
<script> // Script 2
// Use the variable declared in Script 1:
alert(root_scope); // This variable is declared at root
// Note: declaring at root is the same as assigning to window
alert(window.root_scope); // This variable is declared at root
alert(typeof non_root); // undefined
</script>
Related
I have 2 .js files in the html document like this:
<script type="text/javascript" src="js/1.js"></script>
<script type="text/javascript" src="js/2.js"></script>
That document also have an iframe. I have 2 .js in the iframe aswell:
<script type="text/javascript" src="js/2.js"></script>
<script type="text/javascript" src="js/3.js"></script>
So 2.js is in both documents. My plan was to make that to connect them.
I can not put 3.js in both documents because it will mess up stuff.
1.js got a variable. I want to use that variable in 3.js. But i can't figure out how to pass a variable from 1.js to 3.js.
Is this even possible?
*The variable is declared in 1.js.
You can not "pass" variables through file references. You would need to add code to pass data from the parent frame to the iframe.
If the variable is global it is
//from the iframe
var theVariable = window.parent.yourVaraibleName;
//from the parent
var theVariable = document.getElementById("iframeId").contentWindow.yourVaraibleName;
Why not using jQuery cookies to pass the variables? Even within the multiple pages. Once you pass the variable you can destroy the cookie.
jus create a global variable, don't use var keyword
myGlobal = "probably not a good idea but still";
You cannot pass variables from one js file to the other
Javascript variables are stateless so they wont be retained.
If you are using .Net then you can make use of Session variables to solve this purpose.
If you use MVC you can go for viewbag or viewdata.
If its a must then declare some variable in the homepage, then assign the value to be passed to the variable in home page and then call the function in 3.js passing this parameter.
Iam a new guy in JS and iam doing a mobile project in phonegap, i want to know how to keep a variable in overall page scope, not global variable since it will eat lot of memory which is not acceptable for a mobile developer, i have two or more JS tags in a page as shown,
<script type="text/javascript">
// script one here
</script>
<html> //html block here </html>
<script type="text/javascript">
// script two here
</script>
so i request your valuable suggestion & help. Thanks!
"Overall Page scope" is global scope.
JavaScript scoping (generally, except for specific esoteric scopes*) works in two ways:
Global scope
Closure scope (the scope created by a function)
Since you can't share a function over script tags, a global is your only choice.
Consider passing messages to share data instead of a global.
Here is how something like this could be done with message passing:
Script 0:
window.pubsub = (function(){
var subscribers = [];
return {
subscribe:function(user){
subscribers.push(user);
},
publish:function(message,data){
subscribers.forEach(function(elem){
elem.onMessage(data);
});
}
};
})();
Script 1:
(function(pubsub){
var someObject = {}; // to share state
//code here
pubsub.subscribe(someObject);
someObject.onMessage = function(){
//whatever you do when you get a message
};
})(window.pubsub);
Script 2 would be identical, only it would handle messages differently.
This way, you have one global variable (if that's too much, you can even delete window's reference to it after subscribing script 2, which would mean no globals at all)
*technically try/catch and with also introduce scope, but they're very rare and should not be used like this
I'm using jQuery Mobile Ajax navigation feature, And I need to change a variable that is defined inside external js file, So I can't put my definition before I load that js file...
So, How to change value of a variable for external javascript file after the js file is defined?
(That external js file includes events)
So this question is not duplicate of that question.
Update
My JS File contains events, something like this: $(document).on('mousemove','#main',function() { /*something*/} );
And I need that variable. Is it possible to pass variable to that?
I have tried simply changing that variable i = 5;, but I'm getting undefined error.
Update 2
The external JS file is something for some pages that are almost same, but a little different, just one or two parameters.
And I simply want to pass the parameters to that JS file. Is it possible? How?
Let's assume http://www.example.com/external.js defines variable foo, which you want to change.
<script src="http://www.example.com/external.js"></script>
<script type="text/javascript">
foo = "my new value";
</script>
This assumes that external.js defined foo in the global scope. If it's defined in an anonymous function or similar, you won't be able to change the value.
Depending on what you're doing, you can just set the variable and it'll work. Example:
// JS file
blah = "Hello";
function doSomething() {
alert(blah);
}
// HTML file
blah = "I'm a fish";
doSomething(); // alerts "I'm a fish";
Alternatively, pass the variable as an argument to relevant functions instead of using global variables.
I am currently coding in this way:
<script type="text/javascript">
var linkObj;
Is this a safe way to store data? My concern is what if a jQuery or other plug-in was to also use the variable linkObj. Also if I declare my variable like this then can it also be seen by other functions in scripts located in other js files that I include?
$(document).ready(function(){
var linkObj;
});
as long as you use the var keyword, any variable defined in that scope won't be accessible by other plugins.
I you declare a variable this way it will be accessible to all scripts running on the page.
If you just want to use it locally, wrap it in a function:
(function() {var linkObj; ... })()
However, this way nothing outside of the function will be able to access it.
If you want to explicitly share certain variables between different scripts, you could also use an object as a namespace:
var myProject = {}
myProject.linkObj = ...
This will minimize how many global names you have to rely on.
Wrap it in a closure:
<script type="text/javascript">
(function() {
var linkObj;
// Rest of your code
})();
</script>
This way no script outside your own will have access to linkObj.
Is this a safe way to store data?
This is not storing data per se, it's only declaring a variable in a script block in what I assume is an HTML page. When you reload the page in the future, it will not hold previous values.
My concern is what if a jQuery or other plug-in was to also use the variable linkObj.
That's a valid concern, like others have pointed out. However, you would expect plugins not to rely on scope outside the plug-in. This shouldn't impact a lot as good plug-in design would likely prevent this from happening.
Also if I declare my variable like this then can it also be seen by other functions in scripts located in other js files that I include?
Yes. As long as their execution is triggered after your script block gets loaded. This normally follows the order in which your script declaration appears in the page. Or regardless of the order they appear on the page if they are executed, for example, after the jQuery DOM 'ready' event.
It's common to hear that is good to avoid 'global namespace pollution', which relates to this concern. To accomplish that you can use a function to contain code, and directly invoke that function in your script block.
(function () {
var a = 1; // the scope is within the function
alert('The variable a is equal to: ' + a);
}) (); // the parenthesis invoke the function immediately
I need to send data in a HTML page to a script file that is loaded in that page. The simplest way i can think of is to use a global variable which is defined in the page and accessed in the script file.
We all know global state is bad, so i started thinking about the options available for passing data from HTML page to script file without using global state. I cant find (or think of) any.
I am curious whether this is possible. Any ideas?
It really depends what you're doing. In general, I wouldn't advise this methodology, but it's something to consider depending on your circumstances. For the sake of this example, I'll assume you're using jQuery (if not, replace the document.ready with whatever you want to use for onDOMReadyStateChange monitoring).
In the HTML:
<script type='text/json-data' id='some_data_set'>
{ 'foo': 'bar', 'baz': 1 }
</script>
In the JavaScript:
$(function() {
var myData = JSON.parse($('script#some_data_set').html());
// YOUR CODE GOES HERE
});
Nope. All the javascript scope starts from a global level, therefore you must have at least one global reference to your data.
Let's say you wanted to store a list of products and events:
var myGlobalData = { "products":<products>, "events":<events> };
Where <products> and <events> are two different data blocks.
If you're paranoid on global objects, you can simply delete the reference point (thus it's contents) after you finished using it, as follows:
delete window.myGlobalData;
One option is to scope your data. For example, in JS file you can define an object like:
var processor = {
function setData(o) { // do stuff
}
};
Then in your HTML you know that the data is scoped to the processor. So you can do something like:
processor.setData({someData});