如何优化这个?

时间:2015-01-19 10:49:48

标签: javascript jquery

这是适用于iPhone的大型天气小部件的一部分。 虽然下面的代码工作正常但我想知道如何优化这个,所以我没有两次失败功能? 感谢。

function updateWeather() {
var files = "widgetweather" + xmlnumber + ".xml";
if (typeof groovyAPI !== 'undefined') { 
    groovyAPI.do ({ read: files }, function(data) { weatherHandler(data);
    }).fail( function () {
        document.getElementById("Day0desc").innerHTML = "No widgetweather.xml file !";
        document.getElementById("WeatherInfoBG").style.display = "none";
        document.getElementById("forecastBG").style.display = "none";
        document.getElementById("hourlyforecastBG").style.display = "none";
        document.getElementById("mooninfoBG").style.display = "none"; 
    });
} else { 
    if (XML_TEST == true) { url = files; } else { url = "file:///private/var/mobile/Documents/" + files; }
        jQuery.get(url, function(data) { weatherHandler(data);
        }).fail( function () {
        document.getElementById("Day0desc").innerHTML = "No widgetweather.xml file !";
        document.getElementById("WeatherInfoBG").style.display = "none";
        document.getElementById("forecastBG").style.display = "none";
        document.getElementById("hourlyforecastBG").style.display = "none";
        document.getElementById("mooninfoBG").style.display = "none"; 
    }); 
} 
// REINITIALIZE THE TIMER TO NOT LAUNCH MULTIPLE INSTANCES OF THE FUNCTION  
clearTimeout(refreshTimer); 
refreshTimer = setTimeout(updateWeather, 30*1000);
}

1 个答案:

答案 0 :(得分:3)

function updateWeather() {
var files = "widgetweather" + xmlnumber + ".xml";
if (typeof groovyAPI !== 'undefined') { 
    groovyAPI.do ({ read: files }, function(data) { weatherHandler(data);
    }).fail(noWidget);
} else { 
    if (XML_TEST == true) { url = files; } else { url = "file:///private/var/mobile/Documents/" + files; }
        jQuery.get(url, function(data) { weatherHandler(data);
        }).fail(noWidget);
} 
// REINITIALIZE THE TIMER TO NOT LAUNCH MULTIPLE INSTANCES OF THE FUNCTION  
clearTimeout(refreshTimer); 
refreshTimer = setTimeout(updateWeather, 30*1000);
}

function noWidget(){
        document.getElementById("Day0desc").innerHTML = "No widgetweather.xml file !";
        document.getElementById("WeatherInfoBG").style.display = "none";
        document.getElementById("forecastBG").style.display = "none";
        document.getElementById("hourlyforecastBG").style.display = "none";
        document.getElementById("mooninfoBG").style.display = "none"; 
}