[javascript]Hjälp med att förstå bit av kod
Hej,
Så jag är ny till javascript och behöver ny hjälp att förstå en bit av kod, jag håller på att jobba mot en API från trafikvärket, största delen av koden är copy-pasta d från deras exempelkod för javascript, jag har lyckas lista ut hur stora delar av den funkar då jag har lite erfarenhet av andra programmeringspråk.
Det koden gör är att skriva ut diverse info om tåg vid sökt station. Uppdelad i avgående och ankommande tåg.
Hela koden:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui....">
<style>
table
{
border: 1px solid #000000;
border-collapse: collapse;
border-spacing: 0px;
}
table td
{
padding: 8px 8px;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript">
var Stations = new Array();
$(document).ready(function () {
$.support.cors = true; // Enable Cross domain requests
try {
$.ajaxSetup({
url: "http://api.trafikinfo.trafikverket.se/v1/data.json",
error: function (msg) {
if (msg.statusText == "abort") return;
alert("Request failed: " + msg.statusText + "\n" + msg.responseText);
}
});
}
catch (e) { alert("Ett fel uppstod vid initialisering."); }
// Create an ajax loading indicator
var loadingTimer;
$("#loader").hide();
$(document).ajaxStart(function () {
loadingTimer = setTimeout(function () {
$("#loader").show();
}, 200);
}).ajaxStop(function () {
clearTimeout(loadingTimer);
$("#loader").hide();
});
// Load stations
PreloadTrainStations();
});
function PreloadTrainStations() {
// Request to load all stations
var xmlRequest = "<REQUEST>" +
// Use your valid authenticationkey
"<LOGIN authenticationkey='ce64272a803b49ceae68360cc8de3f09' />" +
"<QUERY objecttype='TrainStation'>" +
"<FILTER/>" +
"<INCLUDE>Prognosticated</INCLUDE>" +
"<INCLUDE>AdvertisedLocationName</INCLUDE>" +
"<INCLUDE>LocationSignature</INCLUDE>" +
"</QUERY>" +
"</REQUEST>";
$.ajax({
type: "POST",
contentType: "text/xml",
dataType: "json",
data: xmlRequest,
success: function (response) {
if (response == null) return;
try {
var stationlist = [];
$(response.RESPONSE.RESULT[0].TrainStation).each(function (iterator, item)
{
// Save a key/value list of stations
Stations[item.LocationSignature] = item.AdvertisedLocationName;
// Create an array to fill the search field autocomplete.
if (item.Prognosticated == true)
stationlist.push({ label: item.AdvertisedLocationName, value: item.LocationSignature });
});
fillSearchWidget(stationlist);
}
catch (ex) { }
}
});
}
function fillSearchWidget(data) {
$("#station").val("");
$("#station").autocomplete({
// Make the autocomplete fill with matches that "starts with" only
source: function (request, response) {
var matches = $.map(data, function (tag) {
if (tag.label.toUpperCase().indexOf(request.term.toUpperCase()) === 0) {
return {
label: tag.label,
value: tag.value
}
}
});
response(matches);
},
select: function (event, ui) {
var selectedObj = ui.item;
$("#station").val(selectedObj.label);
// Save selected stations signature
$("#station").data("sign", selectedObj.value);
return false;
},
focus: function (event, ui) {
var selectedObj = ui.item;
// Show station name in search field
$("#station").val(selectedObj.label);
return false;
}
});
}
function Search() {
var sign = $("#station").data("sign");
// Clear html table
$('#timeTableDeparture tr:not(:first)').remove();
// Request to load announcements for a station by its signature
var xmlRequest = "<REQUEST version='1.0'>" +
"<LOGIN authenticationkey='ce64272a803b49ceae68360cc8de3f09' />" +
"<QUERY objecttype='TrainAnnouncement' " +
"orderby='AdvertisedTimeAtLocation' >" +
"<FILTER>" +
"<AND>" +
"<OR>" +
"<AND>" +
"<GT name='AdvertisedTimeAtLocation' " +
"value='$dateadd(-00:15:00)' />" +
"<LT name='AdvertisedTimeAtLocation' " +
"value='$dateadd(14:00:00)' />" +
"</AND>" +
"<GT name='EstimatedTimeAtLocation' value='$now' />" +
"</OR>" +
"<EQ name='LocationSignature' value='" + sign + "' />" +
"<OR>" +
"<EQ name='ActivityType' value='Ankomst' />" +
"<EQ name='ActivityType' value='Avgang' />" +
"</OR>" +
"</AND>" +
"</FILTER>" +
// Just include wanted fields to reduce response size.
"<INCLUDE>InformationOwner</INCLUDE>" +
"<INCLUDE>AdvertisedTimeAtLocation</INCLUDE>" +
"<INCLUDE>TrackAtLocation</INCLUDE>" +
"<INCLUDE>FromLocation</INCLUDE>" +
"<INCLUDE>ToLocation</INCLUDE>" +
"<INCLUDE>AdvertisedTrainIdent</INCLUDE>" +
"<INCLUDE>EstimatedTimeAtLocation</INCLUDE>" +
"<INCLUDE>ActivityType</INCLUDE>" +
"<INCLUDE>LocationSignature</INCLUDE>" +
"</QUERY>" +
"</REQUEST>";
$.ajax({
type: "POST",
contentType: "text/xml",
dataType: "json",
data: xmlRequest,
success: function (response) {
if (response == null) return;
if (response.RESPONSE.RESULT[0].TrainAnnouncement == null)
jQuery("#timeTableDeparture tr:last").
after("<tr><td colspan='4'>Inga avgångar hittades</td></tr>");
try {
renderTrainAnnouncement(response.RESPONSE.RESULT[0].TrainAnnouncement);
}
catch (ex) { }
}
});
}
function renderTrainAnnouncement(announcement) {
$(announcement).each(function (iterator, item) {
var advertisedtime = new Date(item.AdvertisedTimeAtLocation);
var hours = advertisedtime.getHours()
var minutes = advertisedtime.getMinutes()
var esttime = new Date(item.EstimatedTimeAtLocation);
var esthours = esttime.getHours()
var estminutes = esttime.getMinutes()
if (minutes < 10) minutes = "0" + minutes
if (estminutes < 10) estminutes = "0" + estminutes
var toList = new Array();
$(item.ToLocation).each(function (iterator, toItem) {
toList.push(Stations[toItem]);;
});
var owner = "";
if (item.InformationOwner != null) owner = item.InformationOwner;
if (item.ActivityType == "Avgang") jQuery("#timeTableDeparture tr:last").
after("<tr><td>" + item.ActivityType + "</td><td>" + hours + ":" + minutes + "</td><td>" + esthours + ":" + estminutes + "</td><td>" + item.LocationSignature +
"</td><td>" + owner + "</td><td style='text-align: center'>" + item.TrackAtLocation +
"</td><td>" + item.AdvertisedTrainIdent + "</td>" );
if (item.ActivityType == "Ankomst") jQuery("#timeTableAnkomst tr:last").
after("<tr><td>" + item.ActivityType + "</td><td>" + hours + ":" + minutes + "</td><td>" + esthours + ":" + estminutes + "</td><td>" + toList.join(', ') +
"</td><td>" + owner + "</td><td style='text-align: center'>" + item.TrackAtLocation +
"</td><td>" + item.AdvertisedTrainIdent + "</td>" );
});
}
</script>
</head>
<body>
<div>
<input id="station" type="text" />
<input type="button" value="Visa" onclick="javascript: Search()" />
<span id="loader" style="margin-left: 10px">Laddar data ...</span>
</div>
<div id="result">
<h3>Ankomande tåg</h3>
<table border="1" id="timeTableAnkomst">
<tr>
<th scope="col" style="width:40px;">ankomst/avgong</th>
<th scope="col" style="width:40px;">Tid</th>
<th scope="col" style="width:40px;">Est</th>
<th scope="col" style="width:200px;">Från</th>
<th scope="col" style="width:80px;">Ägare</th>
<th scope="col" style="width:80px;">Spår</th>
<th scope="col" style="width:80px;">TågID</th>
</tr>
</table>
<h3>Avgående tåg</h3>
<table border="1" id="timeTableDeparture">
<tr>
<th scope="col" style="width:40px;">ankomst/avgong</th>
<th scope="col" style="width:40px;">Tid</th>
<th scope="col" style="width:40px;">Est</th>
<th scope="col" style="width:200px;">Till</th>
<th scope="col" style="width:80px;">Ägare</th>
<th scope="col" style="width:80px;">Spår</th>
<th scope="col" style="width:80px;">TågID</th>
</tr>
</table>
</div>
</body>
</html>
Delen jag behöver hjälp är:
var toList = new Array();
$(item.ToLocation).each(function (iterator, toItem) {
toList.push(Stations[toItem]);;
Som jag förstår det så spar den namnet på stationen som tåget ska åka istället för bara signaturen, vilket är det ToLocation returnar, jag fårstår dock inte hur den gör detta, för hittar inte hur den vet stationsnamnet och hur den biten av koden byter från signatur till namn. För det jag vill göra är att den gör samma sak fast för vart tåget kom ifrån (FromLocation). någon som förstår och kanske kan hjälpa?