Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton pattern javascript

I'm new to javascript, and I found that I don't know an appropriate way to get an instance of the same variable repetedly. I am opening an Xml file with this:

function testXML(){
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","../res/data.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
return xmlDoc;
}

I added the return so I can pick that xml file and make some searches to load some lists with data. The problem is that each time I wanna take the xml file for reading some data I call this method, which does not only return me the xml, it alse does the IF/Else and openfile etc,etc... which I guess it's not that appropriate.

So how can I make a method that just returns me the xml file,so I can only open it once? Also, it's safe to open the xml file once and load it into a variable, let's say in index.html, and then navigate to other htmls without losing that variable value(the xml file) ?

Thanks!!

like image 415
Golan_trevize Avatar asked Aug 05 '26 12:08

Golan_trevize


1 Answers

var xml;

function testXML(){
    if(!xml){
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        } else {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("GET","../res/data.xml",false);
        xmlhttp.send();
        xml = xmlhttp.responseXML;
    }
    // return xml; // You can optionally also return the xml, but it'd be assigned to the variable already, any way.
}

Call that function once, and you can just use the xml variable.

Or, like suggested below, just use testXML() instead of the variable in your code, and un-comment the return.
This ensures you won't run into a undefined xml.

like image 120
Cerbrus Avatar answered Aug 07 '26 01:08

Cerbrus