另一種將錯誤處理程序封裝在閉包中或從目標中檢索ID的方法是寫一個隱藏重試機制的自定義加載程序,這樣就可以像使用普通加載程序那樣使用它。
像這樣的東西(我只是寫了這個在記事本中,那麼它可能有錯誤,但只給你的想法...):
public class ProductDataLoader extends EventDispatcher {
private var _paths:Array;
private var _id:String;
private var _state:int;
private var _loader:URLLoader;
private var _data:Object;
public function get data():Object {
return _data;
}
public function ProductDataLoader(id:String) {
_paths = [
"/path/to/product/",
"/alternate/path/to/product/"
];
_id = id;
_state = -1;
_loader = new URLLoader();
_loader.addEventListener(Event.COMPLETE, handleComplete);
_loader.addEventListener(IOErrorEvent.IO_ERROR, handleError);
}
public function load():void {
if(hasNextPath()) {
_loader.load(new URLRequest(getNextPath()));
} else {
// here, we ran out of paths to try
// you shouldn't get here unless you call loadProduct()
// more than once.
// you should probably throw an error here, but that's up to
}
}
private function hasNextPath():Boolean {
return _state < _paths.length - 1;
}
private function getNextPath():String {
_state++;
return _paths[_state] + _id;
}
private function handleComplete(e:Event):void {
// redispatch the complete event
_data = _loader.data;
dispatchEvent(e);
}
private function handleError(e:Event):void {
if(hasNextPath()) {
loadProduct();
} else {
// we tried all paths without success
// so we just redispatch the error event
dispatchEvent(e);
}
}
}
然後在您的負載功能:
function loadData(productID:String):URLLoader {
var productLoader:ProductDataLoader = new ProductDataLoader(productId);
dataLoader.addEventListener(Event.COMPLETE, parseData);
dataLoader.addEventListener(IOErrorEvent.IO_ERROR, handleDataError);
dataLoader.load();
}
選擇了這一個,因爲它非常簡單,並以最少的代碼量優雅地回答問題。如果我需要使用這個長期計劃,或者如果我打算將它用於多個地方(例如跨不同項目),我可能會使用Juan的解決方案。 – Steropes 2011-01-12 20:53:59
@Steropes,很高興它解決了。我同意 - 胡安的解決方案非常優雅,很好地隱藏了故障轉移功能。 – bedwyr 2011-01-12 22:08:11