I may be missing something obvious here, but how could I rewrite this code so that it doesn't need the theVariable to be a global variable ?
<script language="javascript">
theVariable = "";
function setValue() /* called on page load */
{
/* make ajax call to the server here */
theVariable = "a string of json data waiting to be eval()'d";
}
function getValue()
{
alert(theVariable);
}
</script>
<input type="button" onClick="javascript:getValue()" value="Get the value">
In my actual situation, the setValue function makes an ajax call to the server, receives a json string and the data from that is accessed when you mouseover various parts of the page. I end up using several global variables which works fine, but is messy and I'd like to know if there's a better and more elegant way of doing it ?
I would do something like:
<script language="javascript">
var myApp = function () {
/* theVariable is only available within myApp, not globally
* (unless you expose it)
*/
var theVariable = "";
/* called on page load */
var setValue = function setValue(){
/* make ajax call to the server here */
theVariable = "a string of json data waiting to be eval()'d";
};
var getValue = function getValue() {
alert(theVariable);
// call useless private function
pFunc();
};
var pFunc = function pFunc(){
// this is a hypothetical private function
// it's only here to show you how to do it
// in case you need it
};
// now expose anything you need to be globally available
// basically anything that will be called outside of myApp
return { setValue: setValue, getValue: getValue};
}();
</script>
<input type="button" onClick="myApp.getValue()" value="Get the value">
Then somewhere you would add an event listener or whatever for myApp.setValue() to run it on page load.
If you did:
return this;
Or just left the return statement out completely (which would imply return this)...
Then everything would be globally available as myApp.whatever or myApp[whatever].
If you use jQuery (which you may use for the ajax portion), you can use the .data() method which allows you to assign arbitury data to document elements by key/value.
Becuase javascript is dynamically typed, you can also get an element by name/id and then add a property to that element eg
document.myData = 'xyz';
Finally, you can limit the scope of your variables using something called a closure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With