Jump to content

Untangling callbacks


Jay@TastefulTitles.com

Recommended Posts

I have several different pages that all need access to the same XML data file. I'm trying to use this fairly-standard function to load the file when the page loads. If I call getXMLFile() from within each pageLoadFunction, it works, but I'd like to use it to set up some other vars and avoid duplicating code.

getXMLFile = function(callback) {
	var request = new XMLHttpRequest();
	request.open("GET", "MyFileName.xml");
	request.setRequestHeader("Content-Type", "text/xml");
	request.onreadystatechange = function() {
	if (request.readyState == 4 && request.status == 200) {
		callback(request.responseXML);
        //Does code needed for all pages go here? Or where?
    	}
    };
	request.send();
}

What I would like to do is put something like this in my HTML, using a callback to call the fill function after the file has loaded:

<body onload="openXML(fillPageFunction)">	<!--There is a unique fill function for each page-->

OpenXML() would call getXMLFile() to load the data, then make use of it.

Procedurally, here is what I want to happen:

  1. Use getXMLFile() to load the data file
  2. Go ahead and render page HTML/CSS while file is loading
  3. When file is loaded, use it to fill some global vars needed on all pages
  4. Call a fill function to fill fields on the specific page

I've spent hours studying manuals, tutorials, and examples on using callbacks, but my procedural brain still can't make them work. Can someone familiar with callbacks please show me how I could accomplish this? (Using named functions, rather than anonymous, would probably help to make it clearer to me.)

  • To fill vars needed on all pages, would I put that code right after the line "callback(request.responseXML);"? Or where?
  • To fill fields on specific page I would call a unique fillPage function for each page. Where would I do that? Can I make that function a param to openXML()?

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...