该功能执行以下操作:
如何从函数中获取此对象?
示例代码:
XML文件:
<root>
<config>
<station>Station_One</station>
<station>Station_Two</station>
<station>Station_Three</station>
</config>
</root>
带工作站坐标的JS文件:
var stations = {
'Station_One': {
lat: 78.782762
, lng: 17.917843
, name: 'Nowhere'
},
'Station_Two': {
lat: -0.829439
, lng: -91.112473
, name: 'Isla Isabela'
},
'Station_Three': {
lat: 15.066156
, lng: -23.621399
, name: 'Cape Verde'
}
脚本:
function addRoute() {
xhr = createHttpRequest(); //This function returns an XMLHttpRequest()
var url ="urlhere"; //pretend this is valid
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var doc = xhr.responseXML;
var routeStations={};
config=doc.getElementsByTagName("station");
for (i=0;config.length>i;i++) {
//Successfully extracts station values and stores them in currentStation
var currentStation = config[i].childNodes[0].nodeValue;
//currentStation is then used as a reference to find the values stored in the JS file
var lat = stations[currentStation].lat;
var lng = stations[currentStation].lng;
//routeStations Object is created dynamically
routeStations[currentStation] = {lat: lat, lng: lng}
} //end for loop
//alert(routeStations); routeStations object is created successfully
// but will not be available beyond this point
//return routeStations; did not work for me
} //end readyState && status
} // end onreadystatechange
xhr.open("GET",url,true);
xhr.send(null);
}
如何将此对象用于其他功能?
更具体地说,我想从另一个函数引用这个对象。我计划使用这些协调来使用Google Maps API制作折线。
注意:此函数由onChange事件触发,因此,每次触发事件时,都需要在现有对象之上创建一个新对象。
答案 0 :(得分:0)
function onChangeEventListener(){
addRoute(callbackRoute);
}
function callbackRoute(routeStations){
....
}
function addRoute(callback) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//many code to getting object
callback(routeStations);
}
}
}