Organizational Research By

Surprising Reserch Topic

how to avoid global variables in javascript


how to avoid global variables in javascript  using -'javascript,global-variables'

We all know that global variables are anything but best practice. But there are several instances when it is difficult to code without them. What techniques do you use to avoid the use of global variables?

For example, given the following scenario, how would you not use a global variable?

JavaScript code:

var uploadCount = 0;

window.onload = function() {
    var frm = document.forms[0];

    frm.target = "postMe";
    frm.onsubmit = function() {
        startUpload();
        return false;
    }
}

function startUpload() {
    var fil = document.getElementById("FileUpload" + uploadCount);

    if (!fil || fil.value.length == 0) {
        alert("Finished!");
        document.forms[0].reset();
        return;
    }

    disableAllFileInputs();
    fil.disabled = false;
    alert("Uploading file " + uploadCount);
    document.forms[0].submit();
}


Relevant markup:

<iframe src="test.htm" name="postHere" id="postHere"
  onload="uploadCount++; if(uploadCount > 1) startUpload();"></iframe>

<!-- MUST use inline JavaScript here for onload event
     to fire after each form submission. -->


This code comes from a web form with multiple <input type="file">. It uploads the files one at a time to prevent huge requests. It does this by POSTing to the iframe, waiting for the response which fires the iframe onload, and then triggers the next submission.

You don't have to answer this example specifically, I am just providing it for reference to a situation in which I am unable to think of a way to avoid global variables.
    

asked Sep 16, 2015 by android_master
0 votes
2 views



Related Hot Questions

8 Answers

0 votes
NULL
answered Sep 16, 2015 by kinnari
0 votes
NULL
answered Sep 16, 2015 by dahiyabecomp
0 votes
NULL
answered Sep 16, 2015 by girisha
0 votes
NULL
answered Sep 16, 2015 by ajit.chavhan
0 votes
NULL
answered Sep 16, 2015 by patilkiran.101
0 votes
NULL
answered Sep 16, 2015 by gauravg.gwl
0 votes
NULL
answered Sep 16, 2015 by dhananjayksharma
0 votes
NULL
answered Sep 16, 2015 by akasati02

...