How Do I Make A Global Variable In Javascript?
Solution 1:
The ajax call is asynchrous, so the displayXML() function is called in the init() method before dashboard is actually filled. So do this instead:
var dashboard = newArray();
functioninit() {
getXML(); //1. goto get XML 2.// XML Parser
}
functiongetXML() {
console.log("getXML REACHED");
$.ajax({
type: "GET",
url: "file:///H:/ModelDisplayV1/ModelDisplayV1/files/dashboard.xml",
dataType: "xml",
success: xmlParser
});
}
functionxmlParser(xml) {
dashboard[0] = 7;
console.log(dashboard);
displayXML();
});
}
functiondisplayXML() {
console.log("display xml function reached!!!");
console.log(dashboard);
}
Solution 2:
There's only two kinds of scopes in javascript - global and function. If it's not declared inside a function, it's global. If it's not declared using var, it's also implicitly global.
Solution 3:
The var
keyword declares a variable as local, otherwise you can omit it and it will make it global.
The other option is to insert it into the window object like so:
window.dashboard = new Array();
This is the preferred method for insert variables into the global scope.
Also blah blah blah about not abusing global variables that you probably know.
Solution 4:
if you want Java-like class semantics in javascript look at using the Revealing Module pattern.
http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript
Getting in the habit of correctly organizing your javascript code from the beginning will save you many headaches.
Solution 5:
You need to pass a context
to $.ajax()
$.ajax({
type: "GET",
url: "file:///H:/ModelDisplayV1/ModelDisplayV1/files/dashboard.xml",
dataType: "xml",
context: this,
success: xmlParser
});
Post a Comment for "How Do I Make A Global Variable In Javascript?"